Java | Leetcode Java题解之第279题完全平方数

题目:

题解:

java 复制代码
class Solution {
    public 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;
    }

    // 判断是否为完全平方数
    public boolean isPerfectSquare(int x) {
        int y = (int) Math.sqrt(x);
        return y * y == x;
    }

    // 判断是否能表示为 4^k*(8m+7)
    public boolean checkAnswer4(int x) {
        while (x % 4 == 0) {
            x /= 4;
        }
        return x % 8 == 7;
    }
}
相关推荐
один but you4 分钟前
从可变参数到 emplace:现代 C++ 性能优化的核心组合
java·开发语言
是码龙不是码农31 分钟前
ThreadPoolExecutor 7 个核心参数详解
java·线程池·threadpool
这是程序猿1 小时前
Spring Boot自动配置详解
java·大数据·前端
MY_TEUCK1 小时前
【Java 后端 | Nacos 注册中心】微服务治理原理、选型与注册发现实战
java·开发语言·微服务
m0_629494731 小时前
LeetCode 热题 100-----26.环形链表 II
数据结构·算法·leetcode·链表
小江的记录本2 小时前
【Java基础】Java 8-21新特性:JDK21 LTS:虚拟线程、模式匹配switch、结构化并发、序列集合(附《思维导图》+《面试高频考点清单》)
java·数据库·python·mysql·spring·面试·maven
二宝哥3 小时前
离线安装maven
java·数据库·maven
日月云棠3 小时前
6 高级配置:Spring Boot整合、泛化调用与配置指南
java·后端
云烟成雨TD3 小时前
Spring AI Alibaba 1.x 系列【58】Spring AI Alibaba Builtin Nodes 模块介绍
java·人工智能·spring
wyu729613 小时前
SpringBoot学习记录,一个小项目实战
java