```
public int reverse(int x) {
boolean neg = (x < 0);
int max = Integer.MAX_VALUE / 10;
x = Math.abs(x);
int n = 0;
while (x > 0) {
if (n > max || n == max && x % 10 >= 8)
return 0; // overflow
n = n * 10 + (x % 10);
x = x / 10;
}
return neg ? -1 * n : n;
}
```