给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。
示例1:
输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5
示例2:
输入: 3
输出: False
第一次:直接两个for循环,然后就超时了。第二次:对c进行开方,然后定义两个指针,一个指0,一个值c开方取整的值。
判断两个指针分别平方的和,等于c就返回true,大于c第二个指针就减减,小于c第一个指针就加加。
代码:
public static void main(String[] args) {
int c = 1000000000;
System.out.println(judgeSquareSum(c));
}
public static boolean judgeSquareSum(int c) {
if(c == 0 || c == 1)
return true;
int high = (int) Math.sqrt(c);
int lower = 0;
while(lower < high){
if((lower*lower + high*high) == c){
return true;
}else if((lower*lower + high*high) > c){
high -= 1;
}else{
lower += 1;
}
}
return false;
}
本文介绍了一种判断是否存在两个整数a和b,使得a²+b²等于给定非负整数c的方法。通过定义两个指针,一个从0开始,另一个从c的平方根开始,逐步调整指针位置来寻找可能的整数对。
589

被折叠的 条评论
为什么被折叠?



