Sharing my 4ms C++ solution


  • 0
    T
    class Solution {
    private:
        int newNumber(int a)
        {
            int result=0;
            int A = a;
            while(A>0)
            {
                int b=A%10;
                result = result+b*b;
                A=A/10;
            }
            return result;
        }
        
    public:
        bool isHappy(int n) {
            int num = n;
            unordered_set<int> mySet;
            while(true)
            {
                if(num==1)
                    return true;
                if(mySet.count(num)>0)
                    return false;
                mySet.insert(num);
                num = newNumber(num);
            }
        }
    };

Log in to reply
 

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