Tuesday, August 29, 2017

202. Happy Number

https://leetcode.com/problems/happy-number/description/
Solution 1. Chasing
    inline int squareSum(int n) {
        int n2=0;
        while(n){
            n2 += pow(n%10, 2);
            n /= 10;
        }
        return n2;
    }
    bool isHappy(int n) {
        int slow, fast;
        slow = fast = n;
        do {
            slow = squareSum(slow);
            fast = squareSum(fast);
            fast = squareSum(fast);
        } while(slow != fast);
        if (slow == 1) return 1;
        else return 0;
    }
Solution 2. Use a map to store the square sums. If a sum is already in the map, return false.
    bool happy(int n, unordered_map<int,int> &mp){
        if(n==1) return true;
        if(mp[n]) return false;
        mp[n]++;
        int n2=0;
        while(n){
            n2 += pow(n%10, 2);
            n /= 10;
        }
        return happy(n2, mp);
    }
    bool isHappy(int n) {
        unordered_map<int,int> mp;
        return happy(n, mp);
    }

No comments:

Post a Comment