The key point is how to break endless loop . The easy way is to avoid repeating any interim number used before.


  • 0
    D
      class Solution {
      public:
    bool isHappy(int n) {
    int sum=0;
    
    vector<int> num_list;
    
    while(n && find(num_list.begin(),num_list.end(),n)==num_list.end())
    {
        num_list.push_back(n); 
        sum=0;
        while(n)
        {
        sum+=(n%10) * (n%10);
        n/=10;
        }
    
        if(sum==1)
            return true;
        else 
            n=sum;
    }
    
    return false;
    }
    

    };


Log in to reply
 

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