Skip to content

[633] Sum of Square Numbers

https://leetcode.com/problems/sum-of-square-numbers/description/

  • algorithms
  • Easy (32.47%)
  • Source Code: 633.sum-of-square-numbers.py
  • Total Accepted: 41.7K
  • Total Submissions: 127.5K
  • Testcase Example: '5'

Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c.

Example 1:

Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5

Example 2:

Input: 3 Output: False

python
class Solution(object):
    def judgeSquareSum(self, c):
        """
        :type c: int
        :rtype: bool
        """
        if c < 0: return False

        end = int(pow(c, 1.0/2))
        left, right = 0, end

        while left <= right:
            t = left * left + right * right
            if t == c: return True
            elif t > c: right -= 1
            else:
                left += 1

        return False


# s = Solution()
# s.judgeSquareSum(5)
#

Last updated: