2015年6月9日星期二

LeetCode: Happy Number

Key is how to test the number loops endlessly. Test loop by a hashmap recording all sums appeared. If same sum appear again, it's easy to see the sum of the squares of its digits will loop.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
    int getSum(int n){
        int sum=0;
        while(n){
            sum+=(n%10)*(n%10);
            n=n/10;
        }
        return sum;
    }
    bool isHappy(int n) {
        unordered_set<int> record;
        while(n!=1){
            if(record.count(n)) return false;
            else record.insert(n);
            n=getSum(n);
        }
        return true;
    }
};

没有评论:

发表评论