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

题目:

题解:

cpp 复制代码
class Solution {
public:
    // 判断是否为完全平方数
    bool isPerfectSquare(int x) {
        int y = sqrt(x);
        return y * y == x;
    }

    // 判断是否能表示为 4^k*(8m+7)
    bool checkAnswer4(int x) {
        while (x % 4 == 0) {
            x /= 4;
        }
        return x % 8 == 7;
    }

    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;
    }
};
相关推荐
zfan5201 小时前
python对Excel数据处理(1)
python·excel·pandas
小饕1 小时前
我从零搭建 RAG 学到的 10 件事
python
老歌老听老掉牙1 小时前
PyQt5+Qt Designer实战:可视化设计智能参数配置界面,告别手动布局时代!
python·qt
无限进步_1 小时前
【C++】只出现一次的数字 II:位运算的三种解法深度解析
数据结构·c++·ide·windows·git·算法·leetcode
格鸰爱童话2 小时前
向AI学习项目技能(六)
java·人工智能·spring boot·python·学习
悟空爬虫-彪哥2 小时前
VRChat开发环境配置,零基础教程
python
数据知道2 小时前
《 Claude Code源码分析与实践》专栏目录
python·ai·github·claude code·claw code
曲幽2 小时前
FastAPI+Vue:文件分片上传+秒传+断点续传,这坑我帮你踩平了!
python·vue·upload·fastapi·web·blob·chunk·spark-md5
_深海凉_2 小时前
LeetCode热题100-找到字符串中所有字母异位词
算法·leetcode·职场和发展
木井巳2 小时前
【递归算法】目标和
java·算法·leetcode·决策树·深度优先