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 分钟前
如何为全球业务构建可扩展的“群发国际短信接口”?
java·c++·python·golang·eclipse·php·erlang
张较瘦_1 小时前
[论文阅读] 软件工程 - 供应链 | 从Log4Shell到Go组件漏洞:一篇文看懂开源依赖安全的核心痛点与解决方案
论文阅读·golang·开源
wadesir2 小时前
Go语言反射之结构体的深比较(详解reflect.DeepEqual在结构体比较中的应用)
开发语言·后端·golang
尋有緣2 小时前
力扣1327-列出指定时间段内所有的下单产品
leetcode·oracle·数据库开发
FMRbpm3 小时前
栈练习--------从链表中移除节点(LeetCode 2487)
数据结构·c++·leetcode·链表·新手入门
程序员-King.3 小时前
day109—同向双指针(字符串)—每个字符最多出现两次的最长子字符串(LeetCode-3090)
算法·leetcode·双指针
青山的青衫3 小时前
【单调栈和单调队列】LeetCode hot100+面试高频
算法·leetcode·面试
狗头实习生3 小时前
电话号码字母组合
java·算法·leetcode
sin_hielo4 小时前
leetcode 3432
数据结构·算法·leetcode