Problem overview
The function reverseNumber receives a non-negative integer n, up to 1,000,000,000, and returns the number you get by writing its digits in reverse order. The number 123 gives 321. Zeros at the end of n move to the front of the result, where they don't count, so 120 gives 21. A one-digit number stays the same, and 0 gives 0.
Approach
The function takes the digits off n from the right and puts each one on the right end of a new number. The last digit of n is the first digit of the reversed number, so the order comes out right without any extra work.
Two integer operations do the job:
n % 10is the last digit ofn, andn / 10drops it.result * 10 + digitappends a digit toresult: multiplying by 10 shifts the digits left and leaves a 0 at the end, and adding the digit fills it. For example32 * 10 + 1is 321.
Here is the loop on n = 123, showing the state after each pass:
n=12 result=3
n=1 result=32
n=0 result=321
And on n = 120:
n=12 result=0
n=1 result=2
n=0 result=21
The first digit moved is the 0, and 0 * 10 + 0 is still 0, which is why trailing zeros vanish.
Step by step
- Create
resultas anintstarting at 0. It will hold the reversed number. Ifnis 0, the loop never runs and 0 is the right answer. - Start a
whileloop that runs whilen > 0. - Move the last digit. Set
resulttoresult * 10 + n % 10. - Drop that digit from
n. Setnton / 10. The digit is already insideresult. - Return
resultafter the loop.
The solution in C++
class Solution {
public:
int reverseNumber(int n) {
int result = 0;
while (n > 0) {
result = result * 10 + n % 10;
n = n / 10;
}
return result;
}
};
Some details about this code:
- Operator precedence.
*,/and%bind tighter than+, so the expression means(result * 10) + (n % 10). No parentheses are needed. - Overflow. Signed integer overflow is undefined behaviour in C++. Here it can't happen: the input is at most 1,000,000,000, and reversing a number of nine digits or fewer gives a number of nine digits or fewer, below 1,000,000,000. The only ten-digit input, 1000000000, reverses to 1. The reversed value of a ten-digit number could exceed the
intrange in general, so a version for larger inputs would needlong long. - Integer division.
n / 10between twointvalues discards the remainder, so 123 becomes 12.
Edge cases and common mistakes
- Trailing zeros. 120 gives 21, not 021: a number doesn't keep leading zeros.
- Zero. The loop is skipped and
resultstays 0. - Palindromes. 900000009 reverses to itself, and 987654321 gives 123456789.
- Largest input. 1000000000 gives 1, because the nine zeros come off first and add nothing.
- Swapping the two lines in the loop. If
nis divided beforen % 10is used, the wrong digit is added.
Testing
n = 123gives 321.n = 120gives 21.n = 7gives 7.n = 0gives 0.n = 987654321gives 123456789.n = 1000000000gives 1.
