LC 202. Happy Number

Nilanjan Deb · April 5, 2020

This is my CPP solution.

class Solution {
private:
    vector<int> digitSplit(int n){
        vector<int> ans;
        while(n){
            ans.push_back(n%10);
            n/=10;
        }
        return ans;
    }
public:
    bool isHappy(int n) {
        unordered_map<int,int> umap;
        int res = 0;
        while(1){
            res = 0;
            vector<int> digits = digitSplit(n);
            int k = digits.size();
            for(int i=0;i<k;i++){
                res+=(digits[i]*digits[i]);
            }
            if(res == 1)
                break;
            n = res;
            cout << res << " ";
            if(umap.find(res)==umap.end()){
                umap[res] = res;
                continue;
            }
            if(umap.find(res)!=umap.end()){
                return false;
            }
        }
        return true;
    }
};


Dicussion Forum