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
}
相关推荐
程序员Query5 分钟前
day01-认识Go语言 + golang环境的安装
开发语言·后端·golang
希望我万事顺遂1 天前
力扣hot100-滑动窗口最大值
数据结构·算法·leetcode
喵了几个咪1 天前
GoWind Flow 拆解:一个 Go 工作流引擎与它的双模式设计器
开发语言·人工智能·后端·golang
codeejun1 天前
每日一Go·MySQL-14、慢 SQL 产生原因全解
sql·mysql·golang
是main不是漫1 天前
【双指针|LeetCode1089 复写零】巧用逆向思路,破解原地覆盖陷阱
数据结构·算法·leetcode
Pniubi2 天前
力扣76.最小覆盖子串
算法·leetcode·职场和发展
文丑颜不良啊2 天前
LeetCode2541~2560题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2481~2500题目解析
java·leetcode
文丑颜不良啊3 天前
LeetCode2461~2480题目解析
java·leetcode
文丑颜不良啊3 天前
LeetCode2441~2460题目解析
java·leetcode