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;
    }
};
相关推荐
leoufung3 小时前
用三色 DFS 拿下 Course Schedule(LeetCode 207)
算法·leetcode·深度优先
ID_180079054733 小时前
基于 Python 的 Cdiscount 商品详情 API 调用与 JSON 核心字段解析(含多规格 SKU 提取)
开发语言·python·json
Q_Q5110082854 小时前
python+django/flask+vue的大健康养老公寓管理系统
spring boot·python·django·flask·node.js
我是哈哈hh4 小时前
【Python数据分析】Numpy总结
开发语言·python·数据挖掘·数据分析·numpy·python数据分析
Michelle80234 小时前
24大数据 14-2 函数练习
开发语言·python
qq_381454994 小时前
Python学习技巧
开发语言·python·学习
Ndmzi4 小时前
Matlab编程技巧:自定义Simulink菜单(理解补充)
前端·javascript·python
dagouaofei4 小时前
AI生成个性化年终总结PPT
人工智能·python·powerpoint
苏小瀚5 小时前
[算法]---路径问题
数据结构·算法·leetcode
月明长歌5 小时前
【码道初阶】一道经典简单题:多数元素(LeetCode 169)|Boyer-Moore 投票算法详解
算法·leetcode·职场和发展