给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。
示例1:
输入: 5 输出: True 解释: 1 * 1 + 2 * 2 = 5
示例2:
输入: 3 输出: False
方法一:
class Solution {
public:
bool judgeSquareSum(int c) {
for(int i = sqrt(c); i >= 0; i--)
{
int j = sqrt(c - i * i);
if(i * i + j * j == c)
return true;
}
return false;
}
};
方法二:
class Solution {
public:
bool judgeSquareSum(int c) {
int low = 0;
int high = sqrt(c);
while(low <= high)
{
int mid = low * low + high * high;
if(mid == c)
return true;
else if(mid > c)
{
high--;
}
else
{
low++;
}
}
return false;
}
};