Problem overview
The function reverseNumber receives a non-negative integer n and returns the number you get by writing its digits in reverse order. 123 becomes 321, and 7 stays 7. Zeros at the end of n end up at the front of the reversed number, where they have no value: 120 reversed is 021, which is the number 21. The answer for 0 is 0.
Approach
Work with numbers only, no strings. Two operations take a digit off the right end of num and put it on the right end of the result.
num % 10is the last digit ofnum.result * 10 + digitshifts the digits already inresultone place to the left and puts the new digit in the freed place.
The last digit of n comes off first, and it should be the first digit of the answer, so the order comes out reversed with no extra work. Here is the run for n = 120:
| num | result after the turn |
|---|---|
| 120 | 0 |
| 12 | 2 |
| 1 | 21 |
The first digit moved is 0, and 0 * 10 + 0 is still 0, which is why trailing zeros disappear without any special code.
A common first idea is to turn the number into a string and reverse the characters. That works, but it needs conversions back and forth, and it has to deal with the leading zeros itself. The arithmetic version gets the zero handling for free, because a number never stores leading zeros. It also stays a loop of a few lines, with one multiplication, one remainder and one division per digit.
Step by step
- Copy
nintovar num. Parameters are constants, so the loop works on a variable. - Create
var result = 0to build the reversed number. Forn = 0the loop never runs and 0 is correct. - Loop while
num > 0. - Set
resulttoresult * 10 + num % 10. Operator precedence does the right thing:%binds tighter than+, as*does. - Replace
numwithnum / 10. The digit you just moved is gone fromnum. - Return
result.
The solution in Swift
class Solution {
func reverseNumber(_ n: Int) -> Int {
var num = n
var result = 0
while num > 0 {
result = result * 10 + num % 10
num = num / 10
}
return result
}
}
Swift details worth knowing:
- Overflow traps. Swift's
Intis 64 bits, and arithmetic that overflows stops the program instead of wrapping around. A reversed number with up to 10 digits is at most 9,999,999,999, far below the 64-bit limit, so it is safe here. Forn = 1000000009the result is9000000001, which is larger than any 32-bit integer but fine forInt. - Integer division.
Int / Intdrops the remainder, so123 / 10is 12. - Precedence.
result * 10 + num % 10means(result * 10) + (num % 10).
Edge cases and common mistakes
- Trailing zeros.
120gives 21, and1000000000gives 1. - Zero. The loop is skipped and the function returns 0.
- Palindromes.
999999999reverses to itself. - Reversing the order of the two updates. If
numis divided before its last digit is used, the wrong digit gets moved. - Forgetting
* 10. Adding the digits without shifting gives a digit sum, not a reversal.
Testing
123gives 321.120gives 21.7gives 7.0gives 0.1000000009gives 9000000001.
