# LeetCode 7. Reverse Integer

### Kaitian Xie twitter logo github logo Apr 10・1 min read

LeetCode in Java (8 Part Series)

``````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`.

LeetCode in Java (8 Part Series)

DISCUSS
Classic DEV Post from Nov 29 '18

## Big Tech Company Interview Advice Thread 👋 Hey dev.to reader.

Do you prefer sans serif over serif?

You can change your font preferences in the "misc" section of your settings. ❤️  