[LeetCode] Sum of Square Numbers

 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,判断这个数是否由两个数的平方和组成。

首先对c开方,得到的数i这个i是c中最大的平方根,如果c由两个平方数组成,则这两个数的平方根都必然小于等于i,所以从i~0逐个判断c - i*i是否为平方数,如果是平方数,则返回true。

需要注意判断c是否为0这个初始条件。

class Solution {
public:
    bool judgeSquareSum(int c) {
        if (c == 0)
            return true;
        int i = sqrt(c);
        while (i) {
            int x = c - i * i;
            int t = sqrt(x);
            if (t * t == x)
                return true;
            i--;
        }
        return false;
    }
};
// 6 ms
原文地址:https://www.cnblogs.com/immjc/p/7808186.html