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;
    }
};
相关推荐
hhzz1 小时前
【OpenCV 入门到精通 04】视频入门与绘图交互:从摄像头到鼠标画笔
人工智能·python·opencv·计算机视觉·音视频·交互
Thomas.Sir1 小时前
第40课:TensorFlow|模型推理部署前置知识【离线推理、接口调用基础】
人工智能·python·tensorflow
2601_962387821 小时前
多源数据查询指南:MySQL 联邦、Python 聚合与 Presto 引擎全对比
python·mysql·数据集成·presto·联邦查询
weixin199701080161 小时前
《Mercari OTA 直连接入:日本二手电商出海的API通道与600次/分钟限流实战》(附Python源码)
开发语言·数据库·python
alphaTao2 小时前
LeetCode 每日一题 2026/9/7-2026/9/13
算法·leetcode
半亩码田2 小时前
【.NET新特性·第17篇】EF Core 10 与 Aspire 13.1
python·flask·.net
zhangzeyuaaa2 小时前
AI Agent 执行引擎选型指南:PowerShell / Bash 和 Python,边界与最佳实践
人工智能·python·bash
泡干脆面就番茄2 小时前
04_EigenFace特征脸PCA人脸识别
python·opencv
今儿敲了吗2 小时前
01词频统计器
笔记·python