Wednesday, July 29, 2020

633. Sum of Square Numbers --E

Q:

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:

class Solution {
public:
    bool judgeSquareSum(int c) {
        set<int> S;
        for(int i =0; i <= sqrt(c) ; ++i)// 0 is also counted
        {
            int i2 = i*i;
            S.insert(i2);
            if(S.find(c-i2) != S.end())
                return true;
        }
        return false;
    }
};

----------------错误
1: 一开始没有考虑 0  也可以
2:用i*i, 导致有可能溢出

No comments:

Post a Comment