LeetCode 633. 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 <= 231 - 1
典型的双指针问题,不过多赘述了,但是这里注意,平方之后超过了int的范围,所用要用long类型来解这个题。
class Solution {
public boolean judgeSquareSum(int c) {
long upnum = (long) Math.sqrt(c);
long downnum = 0L;
do{
long sum = upnum*upnum + downnum*downnum;
if (sum == c) return true;
if (sum < c)
downnum++;
else
upnum--;
}while(upnum >= downnum);
return false;
}
}