给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。
示例1:
输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5
示例2:
输入: 3
输出: False
耶耶耶,第一次主动(貌似是的)使用了指针的方法
class Solution {
public boolean judgeSquareSum(int c) {
if(c == 1 || c == 2 || c == 4){
return true;
}
int start = 0;
int end = (int) Math.sqrt(c);
while (start <= end) {
if(start* start + end * end > c){
end--;
}else if (start* start + end* end < c) {
start++;
}else {
return true;
}
}
return false;
}
}
排名很高
排名很高的代码,代码很类似哦
class Solution {
public boolean judgeSquareSum(int c) {
int i=0,j=(int)Math.sqrt(c);
while(i<=j){
int sumPow = i * i + j * j;
if(sumPow == c){
return true;
}else if(sumPow > c){
j--;
}else{
i++;
}
}
return false;
}
}