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;
    }
};
相关推荐
圣保罗的大教堂3 小时前
leetcode 3867. 数对的最大公约数之和 中等
leetcode
To_OC5 小时前
LC 15 三数之和:双指针不难,难的是把去重做对
javascript·算法·leetcode
benchmark_cc6 小时前
如何用 Python + QuantDash 快速构建高胜率“配对交易(Pairs Trading)”策略?
开发语言·人工智能·python·pandas·量化交易·quantdash
Python+998 小时前
Java 枚举类(Enum)详解:从基础到高级应用
java·开发语言·python
G.O.G.O.G8 小时前
LeetCode SQL 从入门到精通(MySQL)06(上)
数据库·sql·mysql·leetcode
dunge20268 小时前
2026年7月最新ChatGPT Plus / Pro 与 Codex:当 AI Agent 最新5.6版本来袭,必须理解事务、幂等与补偿
开发语言·人工智能·python
闪电悠米10 小时前
力扣hot100-56.合并区间-排序详解
数据结构·算法·leetcode·贪心算法·排序算法
小白学大数据10 小时前
两周完成爬虫技术栈升级:Scrapy 迁移 Crawlo 的路径与取舍
爬虫·python·scrapy
用户83562907805110 小时前
使用 Python 在 Excel 中添加和自定义文本框
后端·python
总裁余(余登武)11 小时前
python多个py文件打包【解决exe不能移动运行bug】
python