给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。
示例1:
输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5
示例2:
输入: 3
输出: False
l从0开始,j从比根号c的小的最大的一个整数开始。
如果平方和比c小,则让l+1以使得平方和变大;反之,如果平方和比c大,则让r-1以使得平方和变小。
如果平方和和c相等,则说明是存在的,返回true。如果直到l指针比r还大了也不存在,则返回false。
附上代码:
class Solution {
public boolean judgeSquareSum(int c) {
int sum=0;
if(c<=1)
return true;
int l=0;
int r=(int)Math.pow(c,0.5);
while(l<=r){
sum=l*l+r*r;
if(sum==c)
return true;
if(sum<c)
l++;
else
r--;
}
return false;
}
}