633. 平方數之和
阿新 • • 發佈:2018-12-11
633.平方數之和
給定一個非負整數 c ,你要判斷是否存在兩個整數 a 和 b,使得 a2 + b2 = c。
示例1:
輸入: 5 輸出: True 解釋: 1 * 1 + 2 * 2 = 5
示例2:
輸入: 3 輸出: False
分析: 用左右兩個指標,左指標從0開始向右,右指標從c的開平方數開始向左,若平方和小於c左指標移動,若大於右指標移動,等於則返回。
class Solution {
public:
bool judgeSquareSum(int c) {
if(c<0) return false;
int sq=sqrt(c) ;
int left=0;
int right=sq;
int temp=0;
while(left<=right)
{
temp=left*left+right*right;
if(temp<c) left++;
else if(temp==c) return true;
else right--;
}
return false;
}
};