4ms c++ solution using unordered_map


  • 0
    W

    class Solution {

    public:

    bool isHappy(int n) {
    
        unordered_map<int,int> used;
    
        while(n!=1){
    
            n=cal(n);
    
            if(used.find(n)!=used.end()) return false;
    
            used[n]=n;
    
        }
    
        return true;
    
    }
    
    int cal(int sum){
    
        int p,q,result=0;
    
        p=sum;
    
        while(p>9){
    
            sum=p;
    
            q=sum%10;
    
            p=sum/10;
    
            result=result+q*q;
    
        }
    
        return result+p*p;
    
    }
    

    };


  • 1
    T

    I think you can just use unordered_set


Log in to reply
 

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