Q:
给定一个非负整数 c
,你要判断是否存在两个整数 a
和 b
,使得 a2 + b2 = c。
示例1:
输入: 5 输出: True 解释: 1 * 1 + 2 * 2 = 5
示例2:
输入: 3 输出: False
链接:https://leetcode-cn.com/problems/sum-of-square-numbers/description/
思路:首先是0,如果是0的话返回True,接下来的思路就是,首先对数开方取整,之后比如input = 1000 开方取整 = 31 然后计算 1000 - 31^2 = 39 不是平方数 31 -=1 然后 1000-30^2 = 100 是完全平方数 返回true 遍历一下就好了 代码如下:
class Solution:
def judgeSquareSum(self, c):
"""
:type c: int
:rtype: bool
"""
if c == 0:
return True
temp = int(c**0.5)
while temp >= 1:
if self.is_sqrt(c-temp*temp):
return True
else:
temp -= 1
return False
def is_sqrt(self,n):
a = int(n**0.5)
return a*a == n