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

题目:

题解:

Go 复制代码
// 判断是否为完全平方数
func isPerfectSquare(x int) bool {
    y := int(math.Sqrt(float64(x)))
    return y*y == x
}

// 判断是否能表示为 4^k*(8m+7)
func checkAnswer4(x int) bool {
    for x%4 == 0 {
        x /= 4
    }
    return x%8 == 7
}

func numSquares(n int) int {
    if isPerfectSquare(n) {
        return 1
    }
    if checkAnswer4(n) {
        return 4
    }
    for i := 1; i*i <= n; i++ {
        j := n - i*i
        if isPerfectSquare(j) {
            return 2
        }
    }
    return 3
}
相关推荐
玛丽莲茼蒿5 小时前
Leetcode hot100 每日温度【中等】
算法·leetcode·职场和发展
样例过了就是过了6 小时前
LeetCode热题100 分割等和子集
数据结构·c++·算法·leetcode·动态规划
北顾笙9806 小时前
day38-数据结构力扣
数据结构·算法·leetcode
m0_629494736 小时前
LeetCode 热题 100-----14.合并区间
数据结构·算法·leetcode
xin_nai6 小时前
LeetCode热题100(Java)(5)普通数组
算法·leetcode·职场和发展
水蓝烟雨9 小时前
3337. 字符串转换后的长度 II
算法·leetcode
_日拱一卒9 小时前
LeetCode:226翻转二叉树
数据结构·算法·leetcode
踩坑记录9 小时前
leetcode hot100 64. 最小路径和 medium 递归优化
leetcode·深度优先
lolo大魔王9 小时前
Go语言的并发、协调创建和通信机制
开发语言·golang
样例过了就是过了9 小时前
LeetCode热题100 最长有效括号
c++·算法·leetcode·动态规划