Simple C++ Solution.Very easy to understand


  • 0
    P
        class Solution {
    public:
        long long sqrSum(long long n){
            if(n/10==0)
                return n*n;
            
            long long ans=0;
            while(n){
                int rem = n%10;
                ans += (rem*rem);
                n /= 10;
            }
            return ans;
        }
        
        bool isHappy(int n) {
            if(n==0) return false;
            if(n==1) return true;
            
            bool check[10];
            memset(check,false,sizeof(check));
            check[1] = true;
            check[7] = true;
            
            long long t=n;
            while(1){
                long long sqr = sqrSum(t);
                if(sqr/10==0)
                    return check[sqr];
                t=sqr;
            }
        }
    };
    

Log in to reply
 

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