4ms C++ solution with an extra int vector.


  • 1
    B
    class Solution {
    public:
        vector<int> solutions;
        bool isRepeat(int n, vector<int> solutions){
            for(int i=0;i!=solutions.size();i++){
                if(solutions[i]==n)
                    return true;
            }
            return false;
        }
        
        bool isHappy(int n) {
            if(n==1)
                return true;
            else if(isRepeat(n,solutions))
                return false;
            else{
                solutions.push_back(n);
                int nn=0;
                while(n!=0){
                    nn+= (n%10)*(n%10);
                    n = n/10;
                }
                return isHappy(nn);
            }
            
        }
    };

Log in to reply
 

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