633. 平方数之和
LeetCode刷题打卡第010天 (第1篇) 20210719
注意事项: 因为c为int型,所以当c足够大时,可能存在aa+bb的值大于int范围的情况,因此需要定义为long型
代码1
class Solution {
public:
bool judgeSquareSum(int c) {
long left=0;
long right=(int)sqrt(c);
long sum;
if(c==0) return true;
for(int i=0;i<sqrt(c);i++){
sum=left*left+right*right;
if(sum==c)
return true;
else if(sum<c)
left++;
else
right--;
}
return false;
}
};
代码2
class Solution {
public:
bool judgeSquareSum(int c) {
int m=sqrt(c);
if(c==0) return true;
for(long a=0;a<=m;a++)
{
double b = sqrt(c - a * a); //判断b的值是否为整数
if(b==(int)b) return true;
}
return false;
}
};