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;
}
}
本文解析了如何通过双指针法解决LeetCode题目633,讨论了处理超过int范围的平方计算,并给出了Java代码实现。关键在于理解平方数和目标值的关系,以及长整型的使用。
389

被折叠的 条评论
为什么被折叠?



