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
}
相关推荐
鹿角片ljp5 小时前
LeetCode 46. 全排列|吃透回溯
算法·leetcode·职场和发展
剩下了什么5 小时前
float32 与 float64 精度陷阱:如何在 Go 中避免错误使用
开发语言·后端·golang
.道阻且长.8 小时前
11.LeetCode算法习题讲解--滑动窗口--将x减到0的最小操作数
算法·leetcode·职场和发展
wenyq78 小时前
LeetCode 2460. Apply Operations to an Array
算法·leetcode
青 春 记 忆9 小时前
LeetCode 142. 环形链表 II|Python 解法详解
python·leetcode·链表
小欣加油9 小时前
leetcode3069 将元素分配到两个数组中I
数据结构·c++·算法·leetcode·职场和发展
ttwuai11 小时前
Go 后台接入 SSO 后菜单正常但接口 403,怎么排查权限链路?
开发语言·后端·golang
PC2005-cloud12 小时前
Go学习笔记:基本概念与项目结构——GOPATH、Go Modules 与常用命令
笔记·学习·golang
ttwuai12 小时前
Go 后台图片上传到对象存储后,预览 403/404 怎么排查?
开发语言·golang
nike0good12 小时前
April Fools Day Contest 2026 题解
算法·题解·愚人节比赛