给定一个非负整数 c
,你要判断是否存在两个整数 a
和 b
,使得 a2 + b2 = c。
示例1:
输入: 5 输出: True 解释: 1 * 1 + 2 * 2 = 5
示例2:
输入: 3 输出: False
C
bool judgeSquareSum(int c)
{
int n=(int)sqrt(c);
int left=0;
int right=n;
while(left<=right)
{
int tmp=left*left+right*right;
if(c==tmp)
{
return true;
}
if(tmp>c)
{
right--;
}
if(tmp<c)
{
left++;
}
}
return false;
}
python
class Solution:
def judgeSquareSum(self, c):
"""
:type c: int
:rtype: bool
"""
n=int(c**0.5)
left=0
right=n
while left<=right:
tmp=left**2+right**2
if c==tmp:
return True
if tmp<c:
left+=1
if tmp>c:
right-=1
return False