Java | Leetcode Java题解之第279题完全平方数

题目:

题解:

java 复制代码
class Solution {
    public int numSquares(int n) {
        if (isPerfectSquare(n)) {
            return 1;
        }
        if (checkAnswer4(n)) {
            return 4;
        }
        for (int i = 1; i * i <= n; i++) {
            int j = n - i * i;
            if (isPerfectSquare(j)) {
                return 2;
            }
        }
        return 3;
    }

    // 判断是否为完全平方数
    public boolean isPerfectSquare(int x) {
        int y = (int) Math.sqrt(x);
        return y * y == x;
    }

    // 判断是否能表示为 4^k*(8m+7)
    public boolean checkAnswer4(int x) {
        while (x % 4 == 0) {
            x /= 4;
        }
        return x % 8 == 7;
    }
}
相关推荐
ZGG0034 分钟前
MySQL 索引详解:B+ 树、聚簇索引与最左前缀
java·数据库·mysql
萧瑟余晖13 分钟前
Java深入解析篇五十四之对象模型详解
java·开发语言
张文是假的啊32 分钟前
Java | record | Controller逻辑
java·开发语言
勿忘,瞬间38 分钟前
Mybatis高阶
java·数据库·mybatis
Nil2082 小时前
leetcode 994腐烂的橘子
算法·leetcode·职场和发展
嘻哈baby2 小时前
Go 函数中的参数为什么不支持默认值?
java·开发语言·jvm
慧都小项2 小时前
MyEclipse 2026:当 Agent、MCP 与 Java 26 进入 Eclipse 工作流
java·eclipse·springboot·copilot·myeclipse
CoderYanger3 小时前
前端基础——JavaScript(基础语法)(下篇)
java·开发语言·前端·javascript·程序人生·面试·职场和发展
京师20万禁军教头3 小时前
39面向对象(高级)-设计模式
java·开发语言·设计模式
白山编程大哥3 小时前
Java 迭代器接口详解:从 Iterator 到 ListIterator 的完整指南
java·开发语言·windows