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
}
相关推荐
stand_forever33 分钟前
PHP客户端调用由Go服务端GRPC接口
rpc·golang·php
flashlight_hi2 小时前
LeetCode 分类刷题:3217. 从链表中移除在数组中存在的节点
javascript·数据结构·leetcode·链表
Tisfy2 小时前
LeetCode 2536.子矩阵元素加 1:二维差分数组
算法·leetcode·矩阵
席万里3 小时前
通过Golang订阅binlog实现轻量级的增量日志解析,并解决缓存不一致的开源库cacheflow
缓存·golang·开源
q***46523 小时前
对基因列表中批量的基因进行GO和KEGG注释
开发语言·数据库·golang
柠石榴3 小时前
GO-1 模型本地部署完整教程
开发语言·后端·golang
大Null3 小时前
Linux安装GO环境
linux·golang
小欣加油3 小时前
leetcode 2536 子矩阵元素加1
数据结构·c++·算法·leetcode·矩阵
努力学算法的蒟蒻4 小时前
day14(11.14)——leetcode面试经典150
算法·leetcode
海琴烟Sunshine8 小时前
leetcode 383. 赎金信 python
python·算法·leetcode