Simple cpp solution in 4ms,easy to understand,excited!!!!!


  • 0
    H
    class Solution {
    public:
    bool isHappy(int n) {
        int t=0;
        int num=n;
        while(1)
        {
            if(num/10>0)
            {
                t++;
                num=num/10;
            }
            else
            {
                break;
            }
        }
        if(!t)
        {
            if(n==1||n==7)
                return true;
            else
                return false;
        }
        else
        {
            int *a=new int [t+1];
            for(int i=0;i<=t;i++)
            {
                a[i]=n/pow(10,t-i);
                n=n-a[i]*pow(10,t-i);
            }
            int sum=0;
            for(int i=0;i<=t;i++)
            {
                sum=sum+pow(a[i],2);
            }
            return isHappy(sum);
        }
    }
    

    };


Log in to reply
 

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