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
}
相关推荐
爱coding的橙子16 分钟前
每日算法刷题Day70:10.13:leetcode 二叉树10道题,用时2h
算法·leetcode·深度优先
CoLiuRs39 分钟前
异步任务使用场景与实践
微服务·性能优化·golang
poemyang15 小时前
Goroutine间的“灵魂管道”:Channel如何实现数据同步与因果传递?
golang·并发编程
Lazy龙16 小时前
Golang协程
golang
2351616 小时前
【LeetCode】146. LRU 缓存
java·后端·算法·leetcode·链表·缓存·职场和发展
tkevinjd20 小时前
反转链表及其应用(力扣2130)
数据结构·leetcode·链表
程序员烧烤21 小时前
【leetcode刷题007】leetcode116、117
算法·leetcode
Swift社区1 天前
LeetCode 395 - 至少有 K 个重复字符的最长子串
算法·leetcode·职场和发展
Espresso Macchiato1 天前
Leetcode 3710. Maximum Partition Factor
leetcode·职场和发展·广度优先遍历·二分法·leetcode hard·leetcode 3710·leetcode双周赛167
巴里巴气1 天前
第15题 三数之和
数据结构·算法·leetcode