给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c
https://leetcode-cn.com/problems/sum-of-square-numbers/
//方法1:从0开始遍历到sqrt(c),如果sqrt(c - i * i)是整数,说明可以表示为两个整数的和
public boolean judgeSquareSum1(int c) {
int s = (int)Math.sqrt(c);
for (int i = 0; i <= s; i++){
double j = Math.sqrt(c - i * i);
if (j == (int)j){
return true;
}
}
return false;
}
//方法2:双指针法,在[0,sqrt(c)]内,两个指针分别指向a = 0, b = sqrt(c),如果a * a + b * b = c,就返回true,
//如果a * a + b * b > c,就让b--,如果a * a + b * b < c,就让a++.如果a>b,说明遍历完成仍没有找到,就返回false。
public boolean judgeSquareSum(int c) {
long a = 0;
long b = (long) Math.sqrt(c);
while (a <= b){
if (a * a + b * b > c){
b--;
}else if (a * a + b * b < c){
a++;
}else{
return true;
}
}
return false;
}