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
}
相关推荐
lightqjx14 小时前
【算法】双指针
c++·算法·leetcode·双指针
sin_hielo14 小时前
leetcode 2147
数据结构·算法·leetcode
萌>__<新14 小时前
力扣打卡每日一题——缺失的第一个正数
数据结构·算法·leetcode
萌>__<新15 小时前
力扣打卡每日一题————零钱兑换
算法·leetcode·职场和发展
古城小栈15 小时前
Golang 中 return 与 defer 的 长幼尊卑
golang
重生之后端学习15 小时前
238. 除自身以外数组的乘积
java·数据结构·算法·leetcode·职场和发展·哈希算法
Learner__Q15 小时前
每天五分钟:动态规划-LeetCode高频题_day2
算法·leetcode·动态规划
teamlet17 小时前
Gear DNS - 一个go语言开发的小型dns系统
golang·dns·网络服务
Dream it possible!17 小时前
LeetCode 面试经典 150_字典树_添加与搜索单词 - 数据结构设计(96_211_C++_中等)
c++·leetcode·面试·字典树