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;
    }
};
相关推荐
Dxy123931021614 分钟前
Python 将 JSON 字符串转换为字典
前端·python·json
堕27417 分钟前
java数据结构当中的《Lambda表达式》
java·数据结构·python
努力学算法的蒟蒻30 分钟前
day84(2.12)——leetcode面试经典150
算法·leetcode·面试
程序员酥皮蛋33 分钟前
hot 100 第二十三题 23.反转链表
数据结构·算法·leetcode·链表
小鸡吃米…44 分钟前
TensorFlow - TensorBoard 可视化
python·tensorflow·neo4j
TracyCoder1231 小时前
LeetCode Hot100(51/100)——155. 最小栈
数据结构·算法·leetcode
Y.O.U..1 小时前
力扣刷题-86.分隔链表
算法·leetcode·链表
OPEN-Source1 小时前
给 Agent 安装技能:工具抽象、自动选工具与安全边界
人工智能·python·agent·rag·deepseek
TracyCoder1231 小时前
LeetCode Hot100(52/100)——394. 字符串解码
算法·leetcode·职场和发展
ljxp12345681 小时前
高效删除链表重复节点
python