Start learning free

LESSON 217 OF 291 · WHILE LOOPS - CHALLENGES

Reverse a Number in Scala: Building Digits with * 10

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

    SCALA · WHILE LOOPS - CHALLENGES

    Reverse Number in Scala, explained

    Problem overview

    The function reverseNumber takes a non-negative Int, n, and returns the number you get by writing its digits backwards. For 123 the answer is 321. For 120 the answer is 21: backwards the digits read 0, 2, 1, and a leading zero doesn't count. For 7 it is 7, and for 0 it is 0.

    Approach

    This combines two moves. You already know how to take the last digit off a number: num % 10 reads it and num / 10 drops it. Reversing means the digit that comes off first must become the first digit of the answer, then the next one comes after it, and so on.

    To append a digit to a number being built, shift the number one place left by multiplying by 10, then add the digit. From 32 and the digit 1, 32 * 10 + 1 is 321. Because digits leave num from the right and join result on the right, the order flips by itself.

    Step by step

    1. Copy n into var num, since the parameter can't be reassigned.
    2. Create var result, starting at 0. If n is 0, the loop never runs and 0 is correct.
    3. Write a while loop that runs while num > 0.
    4. Inside, set result to result * 10 + num % 10.
    5. Still inside, set num to num / 10. The digit just moved is gone from num.
    6. After the loop, return result.

    For n = 123:

    Turnnum after the turnresult after the turn
    1123
    2132
    30321

    Why the order comes out reversed

    Taking digits from the right of num is the opposite of how you read it. Building result by appending each digit on the right then reproduces that opposite order. The first digit taken, the last one of n, is shifted left more times than any other digit as later digits arrive, so it ends up in the highest place. The same trick builds a number out of digits in any situation where you know the digits one at a time. Shifting by 10 works because the number is written in base 10: each place is worth ten times the place to its right.

    The solution in Scala

    class Solution {
        def reverseNumber(n: Int): Int = {
            var num = n
            var result = 0
            while (num > 0) {
                result = result * 10 + num % 10
                num = num / 10
            }
            return result
        }
    }
    

    Details that matter in Scala:

    • Operator precedence does the work in result * 10 + num % 10: both * and % bind tighter than +, so it is (result * 10) + (num % 10).
    • Both num and result are var, because they change on every turn.
    • Int overflow wraps silently in Scala. The lesson's inputs go up to 1000000000, whose reverse is 1, so they are safe. But a ten-digit number with a large last digit can overflow: reverseNumber(1999999999) returns 1410065399, not 9999999991, because that value is above the 32-bit limit.

    Edge cases and common mistakes

    • Trailing zeros. For 120 the first digit moved is 0, and 0 * 10 + 0 is still 0, so the zero vanishes. The loop then gives result as 2 and finally 21.
    • Zero. reverseNumber(0) returns 0 without entering the loop.
    • Single digit. 7 gives 7.
    • Multiplying after adding. (result + num % 10) * 10 shifts the new digit too and ends with an extra zero.

    Testing

    reverseNumber(123)        -> 321
    reverseNumber(120)        -> 21
    reverseNumber(7)          -> 7
    reverseNumber(0)          -> 0
    reverseNumber(1000000000) -> 1
    
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free