My 4ms C++ solution


  • 0
    S
    class Solution {
    public:
        bool isHappy(int n) {
            map<int, bool> m;
            while(1){
                if(m.find(n)!=m.end()) return false;
                int tmpbase = n;
                int tmp = n % 10;
                int sum = 0;
                sum += tmp * tmp;
                tmpbase -= tmp;
                tmpbase/=10;
                while(1){
                    if(tmpbase==0) break;
                    tmp = tmpbase % 10;
                    sum += tmp * tmp;
                    tmpbase -= tmp;
                    tmpbase/=10;
                }
    
                if(sum == 1) return true;
                m[n] = false;
                n = sum;
            }
        }
    };

Log in to reply
 

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