Leetcode 633.平方数之和
1 题目描述(Leetcode题目链接)
给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a 2 + b 2 = c a^2 + b^2 = c a2+b2=c。
输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5
输入: 3
输出: False
2 题解
双指针
class Solution:
def judgeSquareSum(self, c: int) -> bool:
i, j = 0, int(c**0.5)
while i <= j:
a = i**2 + j**2
if a == c:
return True
elif a > c:
j -= 1
else:
i += 1
return False
枚举
class Solution:
def judgeSquareSum(self, c: int) -> bool:
i = 0
while i**2 <= c:
if (c-i**2)**0.5 % 1 == 0:
return True
i += 1
return False