题目链接:https://leetcode.com/problems/sum-of-square-numbers/#/description
Given a non-negative integer c
, your task is to decide whether there're two integers a
and b
such that a2 + b2 = c.
Example 1:
Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3 Output: False
class Solution {
public:
bool judgeSquareSum(int c) {
for(long a=0;a*a<=c;a++)
{
int b=c-(int)(a*a);
if(binary_search(0,b,b))
return true;
}
return false;
}
bool binary_search(long s,long e,int n)
{
if(s>e)
return false;
long mid=s+(e-s)/2;
if(mid*mid==n)
return true;
else if(mid*mid>n)
return binary_search(s,mid-1,n);
else if(mid*mid<n)
return binary_search(mid+1,e,n);
return false;
}
};
class Solution {
public:
bool judgeSquareSum(int c) {
for(long long a=0;a*a<=c;a++)
{
int b=c-(long long)(a*a);
if(binary_search(0,b,b))
return true;
}
return false;
}
private:
bool binary_search(long long left,long long right,long long n)
{
while(left<=right)
{
long long mid=left+(right-left)/2;
if(mid*mid==n)
return true;
else if(mid*mid>n)
right=mid-1;
else
left=mid+1;
}
return false;
}
};