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
这个题目认为完全平方数也应返回true, e.g. 4 = 0^2 + 2^2, 我第一次提交代码没有认为这一类也应包括在内.
1 class Solution {
2 public:
3 bool judgeSquareSum(int c) {
4 int up = sqrt(c);
5 int left = 0, right = up;
6 while(left <= right) {
7 if(left * left + right * right == c) {
8 return true;
9 }
10 else if(left * left + right* right < c) {
11 left += 1;
12 }
13 else {
14 right -= 1;
15 }
16 }
17
18 return false;
19 }
20 };