loading...

LeetCode 7. Reverse Integer

algobot76 profile image Kaitian Xie Updated on ・1 min read
public int reverse(int x) {
    int rev = 0;

    while (x != 0) {
        int pop = x % 10;
        x /= 10;

        if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) {
            return 0;
        }
        if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) {
            return 0;
        }

        rev = rev * 10 + pop;
    }

    return rev;
}

Reversing an integer is similar to reversing String. We get the last digit x % 10 and add it to rev. We repeat this process until x is 0. The two if statements are used to prevent integer overflows.

Time Complexity: O(log(x))

Extra Space: O(1)

A note on integer overflows

A integer occurs when the sum of rev * 10 + pop is greater/less than the maximum value (Integer.MAX_VALUE)/the minimum value(Integer.MIN_VALUE). So we need the check the values of rev and pop.

  • If rev > Integer.MAX_VALUE/10 or rev < Integer.MIN_VALUE/10, rev * 10 + pop will overflow.
  • If rev == Integer.MAX_VALUE / 10, pop must be less than or equal to 7 because 2^32 - 1 % 10 == 7.
  • If rev == Integer.MIN_VALUE / 10, pop must be greater than or equal to -8 because -2^32 % 10 == 8.

Discussion

pic
Editor guide