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;
    }
};
相关推荐
qq_1588954111117 小时前
Suno-API 是什么?官方 V6 模型与 Python / TypeScript 接入指南
python·ai音乐·suno api
学无止境小袁同学1 天前
Google ADK 学习指南
python·llm·agent·多agent·google adk·llmagent·agent cli
郝学胜-神的一滴1 天前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
LK_071 天前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
wuyk5551 天前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel
Pniubi1 天前
力扣21合并两个有序链表
算法·leetcode·职场和发展
用户54817845909501 天前
Java 与 Python 在大模型与智能体领域的选型
java·python
文丑颜不良啊1 天前
LeetCode3341~3360题目解析
java·leetcode
yiangL_1 天前
1、Python 输入输出实验|print 与 input 人机交互实践
开发语言·python·人机交互