So we have seen reverse string in earlier post, what about reversing integer instead? Noted that the given data input ranges from Â [âˆ’2^{31}, Â 2^{31 }âˆ’ 1] and that for all the reversed integer overflows, return 0.

So let's start with the basic scenario: non-negative and non-overflow case.

```
public int reverse (int x){
int rev = 0;
while (x > 0){
rev = rev * 10 + x % 10;
x /= 10;
}
return rev;
}
```

Like that, very simple yeah? The basic idea is that as long as the value is larger than 9, we will do some operations to it.

In each loop, we want to get the digit from the end of number by performing a modulus (`mod`

), then we add it to a variable and in next loop, we will multiply it by 10 and continue until the remaining number becomes 0. So for example, the number we want to revert is `123`

:

```
1st loop: 0 * 10 + 123 % 10 = 3
2nd loop: 3 * 10 + 12 % 10 = 32
3rd loop: 32 * 10 + 1 % 10 = 321 (exit)
```

Remember we will have to take care of negative numbers right? So the idea is to check if the input number is less than `0`

, then we use boolean variable to mark it as negative number and revert it to positive number by multiplying `-1`

. Lastly, make sure we remember to multiply `-1`

back before returning our result.

```
boolean isNegative = false;
if(x < 0){
isNegative = true;
x = x * -1;
}
...
if(isNegative){
return rev * -1;
}
return rev;
```

Now, the very last part: * edge cases*. It is really annoying to deal with extreme cases where reverting will actually cause the integer to be overflowed. Here, we check the number whether is is going to be overflowed if we multiply by

`10`

. If it is overflowed, then we return `0`

.See the complete solution below:

```
public int reverse(int x) {
boolean isNegative = false;
if(x < 0){
isNegative = true;
x *= -1;
}
int rev = 0;
while(x > 0){
if(rev > Integer.MAX_VALUE / 10){
return 0;
}
rev = rev * 10 + x % 10;
x /= 10;
}
if(isNegative){
return rev * -1;
}
return rev;
}
```

**IMPORTANT NOTE**: do not multiply `rev`

by `10`

and compare with `Integer.MAX_VALUE`

. Reason being when you multiply `rev`

by `10`

, the number has already been overflowed, hence we can't do it that way.

What we can do here is check if rev is larger than the `Integer.MAX_VALUE`

divided by 10 before we apply multiplication and addition on `rev`

. If the statement is true, we can safely return `0`

then.

The explanation is a bit long but I hope you are able to grasp something from this post. Cheers!

*Post was published on **, last updated on *.

Like the content? Support the author by paypal.me!