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;
    }
};
相关推荐
shangyingying_112 小时前
图像质量评价(IQA)
人工智能·python·神经网络
OPEN-Source12 小时前
大模型 Agent 实战:多 Agent 太贵太慢?一套系统性的性能与成本优化方案
人工智能·python·agent·rag·deepseek
一阵寒风13 小时前
ComfyUI本地部署指南
开发语言·人工智能·python
高洁0113 小时前
大模型架构演进:从Transformer到MoE
python·深度学习·机器学习·数据挖掘·知识图谱
谁不学习揍谁!13 小时前
基于python机器学习算法的农作物产量可视化分析预测系统(完整系统源码+数据库+详细文档+论文+详细部署教程+答辩PPT)获取方式
python·算法·机器学习
OPEN-Source13 小时前
别为多 Agent 而多 Agent:一套实用的 Agent 架构选型指南
人工智能·python·agent·rag·deepseek
ID_1800790547313 小时前
Python采集京东商品详情:基于官方API的规格与价格获取
开发语言·数据库·python
一次旅行13 小时前
测开每日AI提效指令(Python+pytest专属)
python·pytest·测试总结
大猫子的技术日记13 小时前
Playwright 自动化测试入门指南:Python 开发者的端到端实战
开发语言·人工智能·python
Volunteer Technology13 小时前
LangGraph的WorkFlow(二)
linux·windows·python