[leetcode_202]Happy Number

Determine whether a number n is a happy number. A happy number is defined by repeatedly summing the squares of its digits and checking if the result equals 1. If it doesn’t equal 1, repeat the process. In practice, this process will form a cycle. [This is a guess, not formally proven.]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
    map<int, bool> flag;
    bool isHappy(int n)
    {
        if (n == 1)
        {
            return true;
        }
        map<int, bool>::iterator it = flag.find(n);
        if (it != flag.end())
        {
            return false;
        }
        else
        {
            flag.insert(map<int, bool>::value_type(n, true));
        }
        int tmpNum = 0;
        while (n > 0)
        {
            tmpNum += (n % 10) * (n % 10);
            n /= 10;
        }
        return isHappy(tmpNum);
    }
};