633. Sum of Square Numbers

来源:互联网 发布:sql函数的种类 编辑:程序博客网 时间:2024/05/19 00:48

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

判断一个数c是否能由两个平方数相加得到。使用暴力的方法,令a从0到sqrt(c),判断c-a^2是不是平方数即可。

代码:

class Solution{public:    bool judgeSquareSum(int c)     {        for(int i = 0; i <= sqrt(c); ++i)        {            double d = sqrt(c-i*i);            if(d == int(d))            {                return true;            }        }        return false;    }};