C++ solution with unordered_map and while loop


  • 0
    G

    This solution works.

    class Solution {
    public:
        bool isHappy(int n) {
            unordered_map<int, int> T;
            while(n != 1){
                T[n]++;
                if(T[n] == 2) return 0; //n appears again
                string s = to_string(n);
                int sum = 0;
                for(int i=0; i< s.size(); i++){
                    sum += pow(s[i]-'0', 2);
                }
                n = sum;
            }
            return 1;
        }
    };
    

  • 0
    L
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.