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;
    }
};
相关推荐
孤狼warrior11 分钟前
灰色预测模型
人工智能·python·算法·数学建模
神仙别闹16 分钟前
基于Python实现LSTM对股票走势的预测
开发语言·python·lstm
机器学习之心1 小时前
小波增强型KAN网络 + SHAP可解释性分析(Pytorch实现)
人工智能·pytorch·python·kan网络
JavaEdge在掘金1 小时前
MySQL 8.0 的隐藏索引:索引管理的利器,还是性能陷阱?
python
站大爷IP1 小时前
Python办公自动化实战:手把手教你打造智能邮件发送工具
python
chao_7891 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
GEEK零零七2 小时前
Leetcode 1070. 产品销售分析 III
sql·算法·leetcode
zdw2 小时前
fit parse解析佳明.fit 运动数据,模仿zwift数据展示
python
凌肖战2 小时前
力扣网编程274题:H指数之普通解法(中等)
算法·leetcode
剑桥折刀s2 小时前
Python打卡:Day46
python