Problem overview
ReverseNumber receives a non-negative int n and returns the number with its digits in reverse order. 123 becomes 321. Zeros at the end of n move to the front, where they don't count: 120 reads 021, which is the number 21. A one-digit number, and 0, stay the same.
Approach
Take digits off the right end of n and put each one on the right end of a new number. The first digit removed ends up first in the result, and the last digit removed ends up last, so the order is reversed with no extra work.
n % 10is the last digit ofn.n / 10removes it (integer division drops the remainder).result * 10 + digitappends a digit to the result: multiplying by 10 shifts every digit one place left and leaves a 0 at the end, and adding the digit fills that place.32 * 10 + 1is 321.
Step by step
- Create
resultas anintset to 0. Ifnis 0 the loop never runs and 0 is right. - Write
while (n > 0). Each pass moves one digit. - Set
resulttoresult * 10 + n % 10. The last digit ofnbecomes the last digit ofresult. - Divide
nby 10 and store it back inn. - Return
resultafter the loop.
For n = 120:
| Pass | result after the pass | n after the pass |
|---|---|---|
| 1 | 0 | 12 |
| 2 | 2 | 1 |
| 3 | 21 | 0 |
The first digit moved is the 0, and 0 * 10 + 0 is still 0. That is why the trailing zero of 120 disappears.
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;
}
}
In result * 10 + n % 10, the operators * and % bind tighter than +, and * and % have the same precedence and go left to right. So it means (result * 10) + (n % 10), which is what you want.
Why the digits come out reversed
Look at where each digit lands. In 123, the digit 3 is removed first. At that moment result is 0, so it becomes 3. Then 2 is removed, and 3 * 10 + 2 makes 32. The 3 has moved one place left, and the 2 sits to its right. Finally 1 gives 32 * 10 + 1, which is 321. Every new digit goes to the right of all the earlier ones, so the digit taken first from the right of n ends at the left of the result.
The same two lines of the loop are used for both numbers: n loses its last digit and result gains one. Together they move the digits across without any text or array.
Edge cases and common mistakes
- Trailing zeros.
120gives 21, not 021. A number has no leading zeros, and anintcan't store them. - Zero. The loop doesn't run, and the method returns 0.
- Overflow. Reversing a number can in general produce a value that doesn't fit in an
int:intoverflow wraps silently in C#, with no error. Herenis at most 1,000,000,000, so the reversal has at most 9 significant digits and stays below the limit.999999999gives999999999and1000000000gives 1. - Dividing first. If you drop the digit before using it, the first digit is lost.
Testing
The solution returns 321 for 123, 21 for 120, 7 for 7, 0 for 0 and 1 for 1000000000.
