My force search cpp solution


  • 0
    T
    class Solution {
    public:
    
        bool isHappy(int n) {
            
            if( n == 0 ) return false;
            if( n == 1 ) return true;
            
            int m = n;
            bool happy = false;
            unordered_set<int> visited;
            
            while( visited.count( m ) == 0 )
            {
                if( m == 1 )
                {
                    happy = true;
                    break;
                }
                    
                auto it = happyMap.find(m);
                if( it != happyMap.end() )
                {
                    happy = it.second;
                    break;
                }
                
                visited.insert( m );
                
                int t = 0;
                for( ; m > 0 ; m /= 10 )
                {
                    int k = m % 10;
                    t += k*k; 
                }
                
                m = t;
            }
            
            for( auto v : visited )
                happyMap[v] = happy;
            
            return happy;
        }
        
        unordered_map<int, bool> happyMap;
    };

Log in to reply
 

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