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
}
相关推荐
YuTaoShao8 分钟前
【LeetCode 每日一题】2053. 数组中第 K 个独一无二的字符串
算法·leetcode·职场和发展
毅炼1 小时前
hot100打卡——day09
java·leetcode
想逃离铁厂的老铁1 小时前
Day42 >> 188、买卖股票的最佳时机IV + 309.最佳买卖股票时机含冷冻期 + 714.买卖股票的最佳时机含手续费
算法·leetcode·职场和发展
狐572 小时前
2026-01-17-LeetCode刷题笔记-3047-求交集区域内的最大正方形面积
笔记·算法·leetcode
有一个好名字3 小时前
力扣-咒语和药水的成功对数
java·算法·leetcode
源代码•宸3 小时前
Golang原理剖析(channel面试与分析)
开发语言·经验分享·后端·面试·golang·select·channel
程序员-King.3 小时前
day136—快慢指针—重排链表(LeetCode-143)
算法·leetcode·链表·快慢指针
不穿格子的程序员4 小时前
从零开始写算法——回溯篇1:全排列 + 子集
算法·leetcode·深度优先·回溯
YuTaoShao5 小时前
【LeetCode 每日一题】2975. 移除栅栏得到的正方形田地的最大面积
算法·leetcode·职场和发展
moxiaoran57535 小时前
Go语言中的泛型
golang