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;
    }
}
相关推荐
2401_cf3 小时前
为什么hadoop不用Java的序列化?
java·hadoop·eclipse
帮帮志3 小时前
idea整合maven环境配置
java·maven·intellij-idea
LuckyTHP3 小时前
java 使用zxing生成条形码(可自定义文字位置、边框样式)
java·开发语言·python
北上ing5 小时前
算法练习:19.JZ29 顺时针打印矩阵
算法·leetcode·矩阵
无声旅者6 小时前
深度解析 IDEA 集成 Continue 插件:提升开发效率的全流程指南
java·ide·ai·intellij-idea·ai编程·continue·openapi
XiaoyaoCarter6 小时前
每日一道leetcode
c++·算法·leetcode·职场和发展·二分查找·深度优先·前缀树
Ryan-Joee6 小时前
Spring Boot三层架构设计模式
java·spring boot
Hygge-star6 小时前
【数据结构】二分查找5.12
java·数据结构·程序人生·算法·学习方法
dkmilk6 小时前
Tomcat发布websocket
java·websocket·tomcat
工一木子7 小时前
【Java项目脚手架系列】第七篇:Spring Boot + Redis项目脚手架
java·spring boot·redis