Accepted Java Solution with overflow checking


  • 2
    Y
    public final int tenthMaxValue = Integer.MAX_VALUE / 10;
    
    public int reverse(int x) {
        int sign = 1;
        int digits = 0;
        int result = 0;
        
        if (x < 0) {
            sign = -1;
            digits = x * sign;
        } else {
            digits = x;
        }
        
        while (digits > 0)
        {
            int digit = digits % 10;
            if (result > tenthMaxValue
                || (result == tenthMaxValue && digit > 8))    // overflow
                return 0;
            result = 10 * result + digit;
            digits /= 10;
        }
        
        return result * sign;
    }

  • 0
    C

    sign is not must required in your code. See below:

        public int reverse(int x) {
    	long  result = 0;
    	while( x != 0)
    	{
    		result = result * 10 + x % 10;
    		x = x / 10;
    	}
    
    	if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE)
    	{
    		return 0;
    	}
    
    	return (int)result;
    }

Log in to reply
 

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