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;
    }
};
相关推荐
kcuwu.26 分钟前
Python进阶:生成器与协程,高效并发编程的核心实践
windows·python·php
XiaoQiao66699927 分钟前
python 简单题目练手【详解版】【1】
开发语言·python
ZC跨境爬虫31 分钟前
极验滑动验证码自动化实战:背景提取、缺口定位与Playwright滑动模拟
前端·爬虫·python·自动化
智算菩萨33 分钟前
【Python图像处理】2 数字图像基础与Python图像表示
开发语言·图像处理·python
abant21 小时前
leetcode 114 二叉树变链表
算法·leetcode·链表
xiaoshuaishuai81 小时前
Git二分法定位Bug
开发语言·python
2401_835792542 小时前
FastAPI 速通
windows·python·fastapi
XiYang-DING2 小时前
【LeetCode】 225.用队列实现栈
算法·leetcode·职场和发展
YMWM_2 小时前
export MPLBACKEND=Agg命令使用
linux·python
派大星~课堂2 小时前
【力扣-148. 排序链表】Python笔记
python·leetcode·链表