```
public int reverse(int x) {
int res = 0;
int m = x > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
while (x != 0) {
int r = x % 10;
if(Math.abs(res) > Math.abs(m / 10) || (Math.abs(res) == Math.abs(m / 10) && Math.abs(r) > Math.abs(m % 10)))
return 0;
res = res * 10 + r;
x = x / 10;
}
return res;
}
```