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;
    }
};
相关推荐
麻雀飞吧15 小时前
先判断工具用来学习、开发还是执行
人工智能·python
人邮异步社区15 小时前
学习Python的最佳学习路径是什么?
python·程序员
Navigator_Z17 小时前
LeetCode //C - 1252. Cells with Odd Values in a Matrix
c语言·算法·leetcode
troy12818 小时前
Python 基础语法(九):Django/Flask/FastAPI 三大 Web 框架详细对比解析
python·jupyter·django·flask·github·fastapi
jzshmyt18 小时前
我用 Python 从零“生成“了一个宇宙,然后让它观察自己(v14)
人工智能·pytorch·python·numpy·matplotlib·空间计算·scipy
语戚19 小时前
力扣 1621. 大小为K的不重叠线段的数目:动态规划(Java 实现)
java·算法·leetcode·动态规划·力扣·dp
青山木19 小时前
Hot 100 --- 最长有效括号
java·数据结构·算法·leetcode·动态规划
用户83562907805120 小时前
使用 Python 将 DOCX 转换为 Markdown
后端·python
小玮看世界20 小时前
[Python]ADAS工程实战(三):多传感器扇区统计疑难点全解——归一化、跨边界、去重与置信度
python
这料鬼有毒20 小时前
二刷hot100-1143.最长公共子序列
算法·leetcode·动态规划