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;
    }
}
相关推荐
纪莫7 分钟前
技术面:MySQL(一条SQL在MySQL的执行过程?、MyISAM和InnoDB的区别?数据库事务机制?)
java·数据库·java面试⑧股
闲人编程12 分钟前
Python协程的演进:从yield到async/await的完整历史
java·前端·python·async·yield·await·codecapsule
帅中的小灰灰27 分钟前
C++编程建造器设计模式
java·c++·设计模式
做怪小疯子34 分钟前
LeetCode 热题 100——链表——相交链表
算法·leetcode·链表
动感小麦兜1 小时前
应用-常用工具部署命令
java·开发语言
日日行不惧千万里1 小时前
IDEA 是用什么开发的?
java·ide·intellij-idea
while(努力):进步2 小时前
5G与物联网:连接万物的数字化未来
leetcode
百***06012 小时前
五大消息模型介绍(RabbitMQ 详细注释版)
java·rabbitmq·java-rabbitmq
转转技术团队3 小时前
MyBatis-Plus踩坑血泪史:那些年我们踩过的坑!
java·面试·mybatis
sg_knight3 小时前
IntelliJ IDEA 实用插件:GitToolBox 使用指南
java·ide·git·intellij-idea·插件·gittoolbox