633. Sum of Square Numbers

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

Solution1:(TLE)

class Solution:
    def judgeSquareSum(self, c):
        """
        :type c: int
        :rtype: bool
        """
        r = int(c**0.5) + 1
        for i in range(r):
            for j in range(r):
                if i*i + j*j ==c:
                    return True
        return False

Solution2:

class Solution:
    def judgeSquareSum(self, c):
        """
        :type c: int
        :rtype: bool
        """
        r = int(c**0.5) + 1
        for i in range(r):
            if int((c-i*i)**0.5) == (c-i*i)**0.5:
                return True
        return False

Solution3:

class Solution:
    def judgeSquareSum(self, c):
        """
        :type c: int
        :rtype: bool
        """
        l = 0
        r = int(c**0.5)+1
        while l<=r:
            t = l*l + r*r
            if t==c:
                return True
            elif t>c:
                r -= 1
            else:
                l -= 1
        return False
posted @ 2018-10-05 11:11  bernieloveslife  阅读(81)  评论(0)    收藏  举报