[C++]my code using string to store reversed x


  • 0
      int reverse( int x )
    {
    	if ( INT_MIN == x )
    	{
    		return 0;
    	}
    	int ux = ( x > 0 ) ? x : -x;
    	int flag = ( x > 0 ) ? 1 : -1;
    	int temp = ux;
    	int len = 0;
    	
            //to get the digits of x
            while ( temp )
    	{
    		len++;
    		temp /= 10;
    	}
            
            //if digit<10   no overflow exits
    	if ( len < 10 )
    	{
    		int res = 0;
    		while ( ux )
    		{
    			res = res * 10 + ux % 10;
    			ux /= 10;
    		}
    		return res*flag;
    	}
           //otherwise to consider the possible overflow
    	else
    	{
    		string str1, str;
    
    		int max_tem = INT_MAX;
    		temp = ux;
    		while ( temp )
    		{
    			str1.push_back( temp % 10 + '0' );
    			str.push_back( max_tem % 10 + '0' );
    			temp /= 10;
    			max_tem /= 10;
    		}
    
    		string str_max( str.rbegin( ), str.rend( ) );
    		if ( str1 > str_max )
    		{
    			return 0;
    		}
    		else
    		{
    			int res = 0;
    			while ( ux )
    			{
    				res = res * 10 + ux % 10;
    				ux /= 10;
    			}
    			return res*flag;
    		}
    	}
    }
    

Log in to reply
 

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