Easy to Understand Java Solution


  • 0
    M

    Reverses the integer using a flag to check for negatives, a double to check for overflow, and modulo arithmetic to reverse.

    '''
    public class Solution {

    // Reverses the digits of an integer.
    public int reverse(int x) {
        
        // Stores if number is negative.
        boolean flag = false;
        
        // Checks for negative edge case.
        if (x < 0) {
            flag = true;
            x = Math.abs(x);
        }
        
        // To store modulo.
        int s;
        
        // Accumulators.
        double b = 0;
        int f = 0;
        
        // Reverses x. Keeps an integer f to
        // return and a double d to check if
        // there is integer size overflow.
        while (x > 0) {
            
            s = x % 10;
            
            f *= 10;
            f += s;
            
            b *= 10;
            b += s;
            
            x /= 10;
        }
        
        // If our original number was negative,
        // revert the reversed number to negative.
        if (flag) {
            b *= -1;
            f *= -1;
        }
        
        // Return 0 if overflowing (as specified).
        if (b > Integer.MAX_VALUE || b < Integer.MIN_VALUE) {
            return 0;
        }
        
        return f;
    }
    

    }
    '''


Log in to reply
 

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