您的位置:首页 > 其它

[leetcode]633. Sum of Square Numbers

2017-07-16 20:41 309 查看
题目链接: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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: