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;
    }
};
相关推荐
这个人懒得名字都没写4 小时前
Python包管理新纪元:uv
python·conda·pip·uv
有泽改之_4 小时前
leetcode146、OrderedDict与lru_cache
python·leetcode·链表
im_AMBER4 小时前
Leetcode 74 K 和数对的最大数目
数据结构·笔记·学习·算法·leetcode
是毛毛吧5 小时前
边打游戏边学Python的5个开源项目
python·开源·github·开源软件·pygame
三途河畔人5 小时前
Pytho基础语法_运算符
开发语言·python·入门
长安er5 小时前
LeetCode 206/92/25 链表翻转问题-“盒子-标签-纸条模型”
java·数据结构·算法·leetcode·链表·链表翻转
Benmao⁢5 小时前
C语言期末复习笔记
c语言·开发语言·笔记·leetcode·面试·蓝桥杯
CoderYanger5 小时前
动态规划算法-01背包问题:50.分割等和子集
java·算法·leetcode·动态规划·1024程序员节
独行soc6 小时前
2025年渗透测试面试题总结-275(题目+回答)
网络·python·安全·web安全·网络安全·渗透测试·安全狮
菜鸟233号7 小时前
力扣513 找树左下角的值 java实现
java·数据结构·算法·leetcode