给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。
示例1:
输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5
示例2:
输入: 3
输出: False
1:第一次采用的写法 :
int judgeSquareSum(int c){
int i=0;
int j=(int)sqrt(c);
int num;
while(i<j){
num =i *i + j*j;
if (num==c){
return 0;
}else if (num >c){
j--;
}else {
i++;
}
}
return -1;
}
Line 8: Char 13: runtime error: signed integer overflow: 829921 + 2146654224 cannot be represented in type 'int' (solution.c)
采用这种写法时虽然i*i 和就j*j 的值 不会溢出,但是num 的值会溢出。
2:采用第二种写法
鉴于溢出的情况,采用减法的形式就不会溢出了。
bool judgeSquareSum(int c){
int i=0;
double x =sqrt(c);
int j=(int)x;
while(i<=j){
//num =i * i + j * j;
if ( (c - i*i) == j*j){
return true;
}else if (j *j > (c - i *i)){
j--;
}else {
i++;
}
}
return false;
}