题目:
Given a non-negative integer c
, your task is to decide whether there're two integers a
and b
such
that a2 + b2 = c.
Example 1:
Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3 Output: False
思路:
一个一个试了。这种题目最好是消除不必要的循环,并且少用开方和除法运算,这样可以大大提高效率。
代码:
class Solution {
public:
bool judgeSquareSum(int c) {
int half_c = (c >> 1), sb, b;
for (int a = 0; a * a <= half_c; ++a) {
sb = c - a * a;
b = sqrt(sb);
if (b * b == sb) {
return true;
}
}
return false;
}
};