Problem overview
The method reverseNumber receives a non-negative integer n and returns the number made by writing its digits in reverse order. 123 becomes 321, and 7 stays 7. Zeros at the end of n move to the front of the result, where they have no value: 120 backwards is 021, which is the number 21. For 0 the answer is 0.
Approach
The last digit of n is n % 10, and Math.floor(n / 10) removes it. Taking digits off the right side of n yields them in exactly the order the reversed number needs: the last digit of n becomes the first digit of the result.
To attach each digit to the result, shift the result one place left and put the digit in the empty place at the right: result * 10 + digit. Multiplying by 10 adds a 0 at the end, and the addition fills it with the new digit. For example, 32 * 10 + 1 is 321.
The loop on 120 goes as follows:
| n at the start of the turn | last digit | result after the turn |
|---|---|---|
| 120 | 0 | 0 |
| 12 | 2 | 2 |
| 1 | 1 | 21 |
The first digit moved is the 0, and 0 * 10 + 0 is still 0. That is why trailing zeros disappear without any special code.
Step by step
- Declare
resultwithletas anumber, starting at 0. It builds the reversed number. Ifnis 0 the loop never runs and 0 is correct. - Loop while
n > 0. The last digit comes off first, so the order is right already. - Move the last digit:
result = result * 10 + n % 10. The%operator binds tighter than+, so the remainder is computed first. - Drop the last digit of
n:n = Math.floor(n / 10). - Return
resultafter the loop.
The solution in TypeScript
class Solution {
reverseNumber(n: number): number {
let result: number = 0;
while (n > 0) {
result = result * 10 + n % 10;
n = Math.floor(n / 10);
}
return result;
}
}
- No overflow to fear. A TypeScript
numberis a double, which holds every integer exactly up to 2^53. The reverse of 1999999999, which is within the lesson's limit, is 9999999991, larger than a 32-bit integer can hold, and the function returns it correctly. - Division needs
Math.floor.123 / 10is 12.3, not 12. - Types are labels.
numberdisappears when TypeScript compiles to JavaScript and does not make anything an integer.
Complexity
Time: O(log n). One turn per digit, and a number has about log10(n) digits.
Space: O(1). Two numbers are kept, result and the changing n.
Edge cases and common mistakes
- Zero. The loop is skipped and the function returns 0.
- Trailing zeros. 120 gives 21, and 1000000000 gives 1.
- A palindrome. A number that reads the same both ways, such as 121, returns itself.
- Moving the digit after dropping it. If
nis divided first, the digit has already been lost whenn % 10is read, and the result is wrong. Add the digit, then drop it. - Adding before multiplying.
(result + n % 10) * 10leaves a stray 0 at the end of the answer. - Forgetting
Math.floor.nbecomes a fraction and the loop runs for many extra turns.
Testing
n = 123gives321.n = 120gives21.n = 7gives7.n = 0gives0.n = 1000000000gives1.n = 1999999999gives9999999991.
