14-line simple C++ solution


  • 0
    L

    Implement the algorithm directly. An interesting point is I can comment out the last return statement. Originally I was thinking the compiler won't let me do that because there will be no explicit exit point. The control flow analysis is smarter than I thought!

    bool isHappy(int n) 
    {
        unordered_set<int> set;
        while(1){
            int nextNum=0;
            if(set.find(n)!=set.end())
                return false;
            else
                set.insert(n);
            while(n){
                nextNum+=pow(n%10,2);
                n/=10;
            }
            if((n=nextNum)==1)
                return true;
        }
        //return false;
    }

Log in to reply
 

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