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
让找出有没有平方和等于目标数。可以采用两边向中间扫描的查找方式,在0和目标数的开方之间。
#include <iostream>
#include <math.h>
using namespace std;
class Solution {
public:
bool judgeSquareSum(int c) {
int a = sqrt(c);
int b = 0;
while (a >= b) {
if (a*a + b*b == c) {
return true;
} else {
if (a*a + b*b < c) {
b++;
} else {
a--;
}
}
}
return false;
}
};
int main() {
Solution s;
s.judgeSquareSum(3);
}
运行结果可能有误差。