[leetcode_202]Happy Number

判断一个数 n 是否是 happy number。happy number 的定义是,各位数依次平方求和,看是否能等于 1,如果不等于 1,再重复上述过程。实际上,这个过程将会是一个循环。[猜的,并没有证明]。

 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);
    }
};
Licensed under CC BY-NC-SA 4.0