Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).
Given x = 123, return 321
Given x = -123, return -321
To reverse an integer, we can perform the following steps, assume variable
a is our result:
- Get the least digit by performing
r = n % 10, the remainder operator
- Add the least digit to our result:
a = a + r
- Divide n by 10:
n = n / 10
- Multiply a by 10, and repeat for next digit
One gotcha is that the reversed integer could overflow an
int. There are two ways to solve this:
- Save the result in a
longinstead of an
int. At the end of reversal, check to see if the result is greater than
- Check for overflow before multiplication or addition. If overflow will occur, then return error.
In the code below, we choose option 2 of checking overflow.
A Java implementation of this algorithm follows.