```
public int reverse(int x) {
if (x == 0 || x == Integer.MIN_VALUE) {
return 0;
}
boolean positive = x > 0;
int result = 0;
//When x!=Integer.MIN_VALUE, -x doesn't overflow
x = positive ? x : -x;
while (x > 0) {
int r = x % 10;
//overflow check
if ((result == Integer.MAX_VALUE / 10 && r > Integer.MAX_VALUE % 10) || (result > Integer.MAX_VALUE / 10)) {
return 0;
}
result = (result * 10 + r);
x = x / 10;
}
return positive ? result : -result;
}
```