您的位置:首页 > 其它

633. Sum of Square Numbers

2017-07-02 17:28 337 查看
题目

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

分析
由于a*a+b*b=c,所以只需要从0到sqrt(c)遍历,求得c-i*i的剩余值,并对其进行开方,如果开方后结果的平方等于开方前结果,则为true,因为sqrt()函数保留整数位,所以不能开方的数结果只是整数位,乘方回去必然不等于开方前的数,本题不排除一个数使用两次的情况。

class Solution {
public:
bool judgeSquareSum(long c) {
for(long i=0;i*i<=c;++i){
long remain=c-i*i;
long r=sqrt(remain);
if(remain==r*r) return true;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: