[C++] with unordered_map to detect cycle


  • 3
    4
    bool isHappy( int n ) {
            
            if( n == 1 ) return 1;
            
            unordered_map< int, bool > m;
            
            int i, temp;
            
            m[n] = 1;
            
            for( ;; ) {
                temp = 0;
                for( ; n; n /= 10 ) {
                    i = n % 10;
                    temp += i * i;
                }
                if ( temp == 1 ) return 1;
                if( m[temp]++ ) return 0;
                n = temp;
            }
        }

  • 0
    L
    This post is deleted!

  • 0
    R

    Hi, Thanks for the clean and simple solution. But I could not understand why the ++ operator here ?

           if( m[temp]++ ) return 0; 
    

  • 0
    4
    if( m[temp]++ ) return 0;
    

    Think about it as

    if( m[temp] ) 
    {
        return 0;
    }
    m[temp] = 1;
    

Log in to reply
 

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