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
}
相关推荐
想吃火锅10053 小时前
【leetcode】14.最长公共前缀js
算法·leetcode·职场和发展
小林ixn4 小时前
LeetCode 206. 反转链表(迭代 + 递归详解)
算法·leetcode·链表
菜鸟‍6 小时前
LeetCode 1 27 和 704 || 两数之和 移除元素 二分查找
算法·leetcode·职场和发展
小小龙学IT6 小时前
Go 泛型深度解析:从设计哲学到工程实践
服务器·数据库·golang
退休倒计时7 小时前
【每日一题】LeetCode 142. 环形链表 II TypeScript
算法·leetcode·链表·typescript
张忠琳8 小时前
【Go 1.26.4】(Part 2) Go 1.26.4 超深度分析 — Runtime GMP 调度器 (proc.go + runtime2.go)
开发语言·golang
sjsjs1111 小时前
力扣3558. 给边赋权值的方案数 I
算法·leetcode·职场和发展
花间相见11 小时前
【LeetCode01】—— 无重复字符的最长子串:滑动窗口经典题详解
python·算法·leetcode
踏着七彩祥云的小丑12 小时前
Go学习第5天:变量作用域 + 数组 + 指针
开发语言·学习·golang·go
言存13 小时前
力扣热题283 移动零
数据结构·算法·leetcode