633.平方数之和
链接:633.平方数之和
难度:Medium
标签:数学、双指针、二分查找
简介:给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c 。
题解 1 - python
- 编辑时间:2024-11-04
- 执行用时:183ms
- 内存消耗:16.25MB
- 编程语言:python
- 解法介绍:遍历每一个数。
class Solution:
    def judgeSquareSum(self, c: int) -> bool:
        a = 0
        while a * a + a * a <= c:
            b2 = c - a * a
            if int(sqrt(b2)) ** 2 == b2: return True
            a += 1
        return False
题解 2 - typescript
- 编辑时间:2021-04-28
- 执行用时:92ms
- 内存消耗:39.5MB
- 编程语言:typescript
- 解法介绍:确定边界值进行逐个比较。
function judgeSquareSum(c: number): boolean {
  let num1 = 0;
  let num2 = ~~Math.sqrt(c) + 1;
  while (num1 <= num2) {
    const sum = num1 ** 2 + num2 ** 2;
    if (sum > c) num2--;
    else if (sum < c) num1++;
    else return true;
  }
  return false;
}