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
}
相关推荐
hanlin039 小时前
刷题笔记:力扣第32题-最长有效括号
笔记·算法·leetcode
All for pursuit.10 小时前
【动态规划-21】312.戳气球
数据结构·c++·算法·leetcode·动态规划
Scintilla_y12 小时前
DAY2 滑动窗口
算法·leetcode·散列表
特立独行的猫a14 小时前
仓颉语言UI开发实战:我用仓颉写了个桌面版力扣
算法·leetcode·ui·tauri·仓颉·cj-tarui
茉莉玫瑰花茶14 小时前
GO [ 标准库 ]
开发语言·后端·golang
y1su14 小时前
Leetcode 动态规划 模板
java·数据结构·算法·leetcode·动态规划
All for pursuit.15 小时前
【位运算-3】136.只出现一次的数字
数据结构·c++·算法·leetcode
All for pursuit.17 小时前
【完结】LeetCodeHot100题 详细解题过程及代码汇总
数据结构·c++·算法·leetcode
mmmmath_317 小时前
LeetCode.101.对称二叉树
数据结构·leetcode
mmmmath_31 天前
LeetCode.637.二叉树的层平均值
算法·leetcode