```
int reverse(int x) {
// First check whether x is negative;
// we can reverse it first and make it negative
// again later.
int signum = x < 0 ? -1 : 1;
x *= signum;
// One at a time, take the units digit from x and
// put it on to reversed, then shift x right one digit.
int reversed = 0;
while (x) {
reversed *= 10;
reversed += x % 10;
x /= 10;
}
// Re-apply the negative sign if there was one.
return reversed * signum;
}
```