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
}
相关推荐
海石5 小时前
1563分的简单题,可能就简单在能被暴力AC
算法·leetcode
海石5 小时前
1400分的dp汗流浃背之【交替子数组计数】
算法·leetcode
退休倒计时9 小时前
【每日一题】LeetCode 437. 路径总和 III TypeScript
算法·leetcode·typescript
tachibana29 小时前
hot100 翻转二叉树(226)
java·数据结构·算法·leetcode
兰令水9 小时前
leecodecode【面试150】【2026.7.9打卡-java版本】
java·数据结构·leetcode·面试·职场和发展
北冥you鱼10 小时前
Go 语言初始化 MySQL 数据库实战指南:从零到生产环境部署
数据库·mysql·golang
Tisfy12 小时前
LeetCode 1288.删除被覆盖区间:排序(非二重循环暴力)
算法·leetcode·题解·排序
知无不研12 小时前
算法:Fizz Buzz解题思路
c++·算法·leetcode
玛卡巴卡ldf15 小时前
【LeetCode 手撕算法】(细节知识点总结)
java·数据结构·算法·leetcode·力扣
名字还没想好☜16 小时前
Go error 处理:errors.Is/As 与错误包装
开发语言·后端·golang·go·错误处理