Skip to content

633. Sum of Square Numbers 👍

  • Time: $O(\sqrt{c})$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  bool judgeSquareSum(int c) {
    unsigned l = 0;
    unsigned r = sqrt(c);

    while (l <= r) {
      const unsigned sum = l * l + r * r;
      if (sum == c)
        return true;
      if (sum < c)
        ++l;
      else
        --r;
    }

    return false;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public boolean judgeSquareSum(int c) {
    int l = 0;
    int r = (int) Math.sqrt(c);

    while (l <= r) {
      final int sum = l * l + r * r;
      if (sum == c)
        return true;
      if (sum < c)
        ++l;
      else
        --r;
    }

    return false;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def judgeSquareSum(self, c: int) -> bool:
    l = 0
    r = math.isqrt(c)

    while l <= r:
      summ = l * l + r * r
      if summ == c:
        return True
      if summ < c:
        l += 1
      else:
        r -= 1

    return False