原题链接:
https://leetcode.cn/problems/sum-of-square-numbers/
解题思路:
- 我们可以先枚举
a
,它的值范围为0 ~ Math.sqrt(c)
。 - 同时查找每个
a
相应的b
,如果b
为整数,则表示找到两个整数。 - 如果枚举完了所有可能的
a
,还未找到b
,表示没有找到。
/**
* @param {number} c
* @return {boolean}
*/
var judgeSquareSum = function (c) {
// 在极限情况下,a^2 + 0 = c,因此a的最大值即为Math.sqrt(c)
let d = Math.sqrt(c)
// a的值可以从0到d,并且是整数
for (let a = 0; a <= d; a++) {
// 计算b的值
let b = Math.sqrt(c - a ** 2)
// 如果b为整数,则表示找到了a和b
if (b === Math.floor(b)) {
return true
}
}
// 退出循环,表示没有找到a和b
return false
}
网友评论