Start learning free

LESSON 218 OF 292 · WHILE LOOPS - CHALLENGES

Reverse a Number in Swift: Building Digits with a while Loop

Practice Read the full explanation

Given a non-negative integer n, return the number you get when you write its digits in reverse order.

Zeros at the end of n move to the front of the reversed number, where they don't count: 120 reversed is 21. If n is 0, the answer is 0.

 

Example 1:

Input: n = 123
Output: 321
Explanation: The digits 1, 2, 3 read backwards are 3, 2, 1.

Example 2:

Input: n = 120
Output: 21
Explanation: Backwards the digits are 0, 2, 1, and 021 is the number 21.

Example 3:

Input: n = 7
Output: 7
Explanation: A number with one digit stays the same.

 

Constraints:

  • 0 <= n <= 109
STEP 1 OF 6
    Ctrl + Enter to check

    SWIFT · WHILE LOOPS - CHALLENGES

    Reverse Number in Swift, explained

    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 % 10 is the last digit of num.
    • result * 10 + digit shifts the digits already in result one 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:

    numresult after the turn
    1200
    122
    121

    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

    1. Copy n into var num. Parameters are constants, so the loop works on a variable.
    2. Create var result = 0 to build the reversed number. For n = 0 the loop never runs and 0 is correct.
    3. Loop while num > 0.
    4. Set result to result * 10 + num % 10. Operator precedence does the right thing: % binds tighter than +, as * does.
    5. Replace num with num / 10. The digit you just moved is gone from num.
    6. 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 Int is 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. For n = 1000000009 the result is 9000000001, which is larger than any 32-bit integer but fine for Int.
    • Integer division. Int / Int drops the remainder, so 123 / 10 is 12.
    • Precedence. result * 10 + num % 10 means (result * 10) + (num % 10).

    Edge cases and common mistakes

    • Trailing zeros. 120 gives 21, and 1000000000 gives 1.
    • Zero. The loop is skipped and the function returns 0.
    • Palindromes. 999999999 reverses to itself.
    • Reversing the order of the two updates. If num is 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

    • 123 gives 321.
    • 120 gives 21.
    • 7 gives 7.
    • 0 gives 0.
    • 1000000009 gives 9000000001.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free