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;
    }
};
相关推荐
pursuit_csdn5 小时前
LeetCode 1022. Sum of Root To Leaf Binary Numbers
算法·leetcode·深度优先
nimadan125 小时前
**AI漫剧软件2025推荐,解锁高性价比创意制作新体验**
人工智能·python
踩坑记录7 小时前
leetcode hot100 35. 搜索插入位置 medium 二分查找
leetcode
yunhuibin8 小时前
GoogLeNet学习
人工智能·python·深度学习·神经网络·学习
易辰君9 小时前
【Python爬虫实战】正则:中文匹配与贪婪非贪婪模式详解
开发语言·爬虫·python
秀儿还能再秀9 小时前
正则表达式核心语法 + Python的 re 库中常用方法
python·正则表达式
xcLeigh9 小时前
Python入门:Python3 正则表达式全面学习教程
python·学习·正则表达式·教程·python3
-海绵东东-9 小时前
哈希表······················
算法·leetcode·散列表
多恩Stone10 小时前
【C++ debug】在 VS Code 中无 Attach 调试 Python 调用的 C++ 扩展
开发语言·c++·python
XW010599910 小时前
4-11判断素数
前端·python·算法·素数