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;
    }
};
相关推荐
鬼手点金1 小时前
Scrapy + Playwright 完整示例(JS 动态渲染网页)
开发语言·javascript·爬虫·python·scrapy·html·json
Forever Nore2 小时前
LeetCode 14 最长公共前缀 - 纵向扫描
linux·服务器·leetcode
vx-程序开发2 小时前
springboot旅游推介平台---附源码24175
java·spring boot·python·spring cloud·eclipse·django·idea
心运软件2 小时前
基于深度学习的宝石图像分类系统
人工智能·python·深度学习·机器学习·分类·数据挖掘
圣保罗的大教堂2 小时前
leetcode 3090. 每个字符最多出现两次的最长子字符串 简单
leetcode
一木 之林2 小时前
AI实战 : Numpy图像处理与深度学习框架
python
c_lb72882 小时前
零基础选策略工具,先分清三件事
人工智能·python
夜雪一千2 小时前
Python如何使用XPath定位没有特征的元素?无id、无class通用定位技巧
开发语言·python
流浪0012 小时前
Python 基础语法(一):常量、变量、输入输出与运算符
开发语言·python
鸿芯微控科技2 小时前
MFC关断后还有流量怎么办?零流量、阀门泄漏、压差与Python分析
c++·python·mfc·质量流量控制器·关断泄漏·零流量测试