My CPP solution, not fast but use no trick !


  • 1
    W
    class Solution {
    public:
        bool isHappy(int n) {
            if(n <= 0)
             return false;
            set<int> recs;
            recs.insert(n);
            while(true){
                n = sumOfDigits(n);
                
                if(recs.find(n) != recs.end())
                    break;
                recs.insert(n);
            }
            return n == 1;
        }
        int sumOfDigits(int n){
            int sum = 0;
            while( n != 0){
                sum += (n % 10)*(n % 10);
                n = n/10;
            }
            return sum;
        }
    };
    

Log in to reply
 

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