633. Sum of Square Numbers
2017-07-02 17:28
337 查看
题目
Given a non-negative integer
that a2 + b2 = c.
Example 1:
Example 2:
分析
由于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;
}
};
Given a non-negative integer
c, your task is to decide whether there're two integers
aand
bsuch
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;
}
};
相关文章推荐
- [leetcode]633. Sum of Square Numbers
- leetcode 633. Sum of Square Numbers 二分查找+勾股定理
- leetcode 633. Sum of Square Numbers
- 633. Sum of Square Numbers标题
- 633. Sum of Square Numbers
- [Leetcode] 633. Sum of Square Numbers 解题报告
- LeetCode 633. Sum of Square Numbers
- leetcode 633. Sum of Square Numbers
- LeetCode 633. Sum of Square Numbers
- 633. Sum of Square Numbers
- 【leetcode】633. Sum of Square Numbers(Python & C++)
- 633. Sum of Square Numbers
- LeetCode 633. Sum of Square Numbers
- leetcode 633. Sum of Square Numbers
- Leetcode 633. Sum of Square Numbers(Easy)
- [leetcode]633. Sum of Square Numbers
- 633. Sum of Square Numbers 平方数之和 看一个数是否能够有两个平方数组成
- 633. Sum of Square Numbers
- [LeetCode]633. Sum of Square Numbers
- 633. Sum of Square Numbers。