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;
    }
};
相关推荐
吴佳浩3 小时前
大模型量化部署终极指南:让700亿参数的AI跑进你的显卡
人工智能·python·gpu
diegoXie4 小时前
Python / R 向量顺序分割与跨步分割
开发语言·python·r语言
七牛云行业应用4 小时前
解决OSError: No space left... 给DeepSeek Agent装上无限云硬盘
python·架构设计·七牛云·deepseek·agent开发
BoBoZz194 小时前
CutWithScalars根据标量利用vtkContourFilter得到等值线
python·vtk·图形渲染·图形处理
失散135 小时前
Python——1 概述
开发语言·python
夏乌_Wx5 小时前
练题100天——DAY23:存在重复元素Ⅰ Ⅱ+两数之和
数据结构·算法·leetcode
萧鼎5 小时前
Python 图像哈希库 imagehash——从原理到实践
开发语言·python·哈希算法
qq_251533595 小时前
使用 Python 提取 MAC 地址
网络·python·macos
Data_agent7 小时前
学术爬虫实战:构建知网论文关键词共现网络的技术指南
python·算法
_一路向北_9 小时前
爬虫框架:Feapder使用心得
爬虫·python