题目描述:
给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。
示例1:
输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5
示例2:
输入: 3
输出: False
解题思路:
设置两个索引begin,end分别从0,c的平方根处开始,计算这两个数的平方和,比c大,end减1,比c小,begin加1.
class Solution(object):
def judgeSquareSum(self, c):
"""
:type c: int
:rtype: bool
"""
begin,end=0,int(math.sqrt(c))
while begin<=end:
if begin**2+end**2>c:
end-=1
elif begin**2+end**2<c:
begin+=1
else:
return True
return False

#评论区答案
if c==0:
return True
for i in range(int(c**0.5)+1):
num = c-i*i
if int(num**0.5)==num**0.5:
return True
return False
#评论区答案
if not c:
return True
k = int(math.sqrt(c))
l = int(math.sqrt(c/2))
for i in range(k,l-1,-1):
m = math.sqrt(c - i*i)
if int(m) == m:
return True
return False
4855




被折叠的 条评论
为什么被折叠?



