Leetcode

Sum of Square Numbers

  • Time:O(\sqrt c)
  • Space:O(1)

C++

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;
  }
};

JAVA

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;
  }
}

Python

class Solution:
  def judgeSquareSum(self, c: int) -> bool:
    l = 0
    r = int(sqrt(c))

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

    return False