633. Sum of Square Numbers

来源:互联网 发布:java web前后端交互 编辑:程序博客网 时间:2024/06/06 09:03

题目

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: 5Output: TrueExplanation: 1 * 1 + 2 * 2 = 5

Example 2:

Input: 3Output: 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;    }};


原创粉丝点击