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;
    }
}
相关推荐
HoneyMoose4 小时前
Jenkins Cloudflare 部署提示错误
java·servlet·jenkins
阿丰资源4 小时前
基于SpringBoot的物流信息管理系统设计与实现(附资料)
java·spring boot·后端
Predestination王瀞潞4 小时前
Java EE3-我独自整合(第四章:Spring bean标签的常见配置)
java·spring·java-ee
overmind4 小时前
oeasy Python 121[专业选修]列表_多维列表运算_列表相加_列表相乘
java·windows·python
资深数据库专家4 小时前
总账EBS 应用服务器1 的监控分析
java·网络·数据库
房开民4 小时前
可变参数模板
java·开发语言·算法
t***5444 小时前
如何在现代C++中更有效地应用这些模式
java·开发语言·c++
_深海凉_4 小时前
LeetCode热题100-最小栈
java·数据结构·leetcode
不知名的忻4 小时前
Morris遍历(力扣第99题)
java·算法·leetcode·morris遍历
daidaidaiyu5 小时前
一文学习入门 ThingsBoard 开源物联网平台
java·mqtt·spring