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
}
相关推荐
执子手 吹散苍茫茫烟波1 小时前
leetcode415. 字符串相加
java·leetcode·字符串
执子手 吹散苍茫茫烟波2 小时前
LCR 076. 数组中的第 K 个最大元素
leetcode·排序算法
山顶风景独好3 小时前
【Leetcode】随笔
数据结构·算法·leetcode
·白小白7 小时前
力扣(LeetCode) ——100. 相同的树(C语言)
c语言·算法·leetcode
墩墩同学9 小时前
【LeetCode题解】LeetCode 74. 搜索二维矩阵
算法·leetcode·二分查找
1白天的黑夜111 小时前
前缀和-560.和为k的子数组-力扣(LeetCode)
c++·leetcode·前缀和
m0_6728137711 小时前
Leetcode-3427变长子数组求和
leetcode
崎岖Qiu11 小时前
leetcode100.相同的树(递归练习题)
算法·leetcode·二叉树·力扣·递归
七七&55617 小时前
2024年08月13日 Go生态洞察:Go 1.23 发布与全面深度解读
开发语言·网络·golang
java坤坤17 小时前
GoLand 项目从 0 到 1:第八天 ——GORM 命名策略陷阱与 Go 项目启动慢问题攻坚
开发语言·后端·golang