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
}
相关推荐
xlp666hub9 小时前
Leetcode第七题:用C++解决接雨水问题
c++·leetcode
花酒锄作田19 小时前
Go - Zerolog使用入门
golang
xlp666hub1 天前
Leetcode第五题:用C++解决盛最多水的容器问题
linux·c++·leetcode
xlp666hub2 天前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
xlp666hub2 天前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
xlp666hub3 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
花酒锄作田13 天前
Gin 框架中的规范响应格式设计与实现
golang·gin
琢磨先生David13 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝13 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll13 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode