LeetCode-633. Sum of Square Numbershttps://leetcode.com/problems/sum-of-square-numbers/
题目描述
Given a non-negative integer c
, decide whether there're two integers a
and b
such that a2 + b2 = c
.
Example 1:
Input: c = 5 Output: true Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: c = 3 Output: false
Constraints:
0 <= c <= 2^31 - 1
解题思路
【C++】
class Solution {
public:
bool judgeSquareSum(int c) {
long left = 0, right = sqrt(c);
while (left <= right) {
long temp = left * left + right * right;
if (temp == c) return true;
if (temp > c) right--;
else left++;
}
return false;
}
};
【Java】
class Solution {
public boolean judgeSquareSum(int c) {
int right = (int) Math.sqrt(c), left = 0;
while (left <= right) {
int tmp = left * left + right * right;
if (tmp == c) {return true;}
else if (tmp < 0 || tmp > c) {right--;}
else {left++;}
}
return false;
}
}