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;
    }
};
相关推荐
宸津-代码粉碎机6 小时前
Spring Boot 4.0虚拟线程实战调优技巧,最大化发挥并发优势
java·人工智能·spring boot·后端·python
知行合一。。。7 小时前
Python--04--数据容器(集合)
python
Captain_Data7 小时前
Python机器学习sklearn线性模型完整指南:LinearRegression/Ridge/Lasso详细代码注释
python·机器学习·数据分析·线性回归·sklearn
爱码小白7 小时前
MySQL 单表查询练习题汇总
数据库·python·算法
北辰alk7 小时前
全网最详实!Python 全家桶框架深度对比:从 Web 开发到 AI 应用,一篇打通选型关
python
xyz_CDragon8 小时前
OpenClaw Skills 完全指南:ClawHub 安装、安全避坑与自定义开发(2026)
人工智能·python·ai·skill·openclaw·clawhub
断眉的派大星8 小时前
pytorch中view和reshape的区别
人工智能·pytorch·python
wsoz8 小时前
Leetcode普通数组-day5、6
c++·算法·leetcode·数组
y = xⁿ8 小时前
【LeetCode】双指针:同向快慢针
算法·leetcode
程序员阿明8 小时前
spring boot3 集成jjwt(java-jwt)版本的
java·spring boot·python