- 题目描述
给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c 。
- 题解
和两数之和那道题目的求解方式类似,需要注意整数的溢出。
- 代码
class Solution {
public:
bool judgeSquareSum(int c) {
long l=0,h=sqrt(c);
while (l<=h){
long s=l*l+h*h;
if (s==c) return true;
else if (s<c) l++;
else h--;
}
return false;
}
};