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;
    }
};
相关推荐
摘星编程28 分钟前
OpenHarmony + RN:Calendar日期选择功能
python
Yvonne爱编码37 分钟前
JAVA数据结构 DAY3-List接口
java·开发语言·windows·python
一方_self38 分钟前
了解和使用python的click命令行cli工具
开发语言·python
小芳矶43 分钟前
Dify本地docker部署踩坑记录
python·docker·容器
We་ct1 小时前
LeetCode 205. 同构字符串:解题思路+代码优化全解析
前端·算法·leetcode·typescript
2301_822366351 小时前
使用Scikit-learn构建你的第一个机器学习模型
jvm·数据库·python
小郎君。2 小时前
【无标题】
python
喵手2 小时前
Python爬虫实战:数据治理实战 - 基于规则与模糊匹配的店铺/公司名实体消歧(附CSV导出 + SQLite持久化存储)!
爬虫·python·数据治理·爬虫实战·零基础python爬虫教学·规则与模糊匹配·店铺公司名实体消岐
喵手2 小时前
Python爬虫实战:国际电影节入围名单采集与智能分析系统:从数据抓取到获奖预测(附 CSV 导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集数据csv导出·采集国际电影节入围名单·从数据抓取到获奖预测
派葛穆3 小时前
Python-PyQt5 安装与配置教程
开发语言·python·qt