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;
    }
};
相关推荐
2301_764441332 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
Billlly2 小时前
ABC 453 个人题解
算法·题解·atcoder
chushiyunen3 小时前
python rest请求、requests
开发语言·python
cTz6FE7gA3 小时前
Python异步编程:从协程到Asyncio的底层揭秘
python
baidu_huihui3 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip
南 阳3 小时前
Python从入门到精通day63
开发语言·python
lbb 小魔仙3 小时前
Python_RAG知识库问答系统实战指南
开发语言·python
FreakStudio3 小时前
MicroPython LVGL基础知识和概念:底层渲染与性能优化
python·单片机·嵌入式·电子diy
素玥4 小时前
实训5 python连接mysql数据库
数据库·python·mysql