题目描述:
给定一个非负整数 c
,你要判断是否存在两个整数 a
和 b
,使得 a2 + b2 = c
。
代码:
class Solution {
public boolean judgeSquareSum(int c) {
long left = 0;
long right = (long) Math.sqrt(c);
while (left <= right) {
long sum = left * left + right * right;
if (sum == c) {
return true;
} else if (sum > c) {
right--;
} else {
left++;
}
}
return false;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/sum-of-square-numbers/solution/ping-fang-shu-zhi-he-by-leetcode-solutio-8ydl/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
值得注意的:采用和双指针发 左指针最小为0 右指针为根号c 有三种情况
(1)左右指针平方和等于C 得到true
(2)平方和小于C a加一
(3)平凡和大于C b减一
如果a=b时仍等于C那么返回 false
原文:https://www.cnblogs.com/ash98/p/14716259.html