Start learning free

LESSON 220 OF 293 · WHILE LOOPS - CHALLENGES

Reverse a Number in Rust: Building Digits with % and /

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

    RUST · WHILE LOOPS - CHALLENGES

    Reverse Number in Rust, explained

    Problem overview

    The function reverse_number takes a non-negative n, at most 1_000_000_000, and returns the number with its digits in reverse order. Zeros at the end of n move to the front, where they don't count: 120 reversed is 21. The reverse of 0 is 0.

    For n = 123 the answer is 321, and a one-digit number stays the same.

    Approach

    The last digit of n is n % 10, and n / 10 removes it. The digits come off from the right, and the last digit of n is the first digit of the answer, so the order is already the one you need.

    To build the answer, keep a variable result. For each digit taken off, multiply result by 10, which shifts its digits one place to the left and leaves a 0 at the end, then add the new digit there. For 123:

    passnum after the passresult after the pass
    1123
    2132
    30321

    Trailing zeros take care of themselves. For 120 the first digit moved is 0, and 0 * 10 + 0 is still 0, so result stays 0 until the 2 arrives. The passes end with result at 21.

    Step by step

    1. Copy n into num with let mut. The loop must change it, and parameters can't be changed.
    2. Create result at 0. It is mutable. If n is 0 the loop never runs, and 0 is the right answer.
    3. Loop while num > 0. The last digit comes off first.
    4. Set result to result * 10 + num % 10. That shifts the digits built so far and appends the new one.
    5. Replace num with num / 10 to drop the digit that was just moved.
    6. Return result as the last expression.

    The solution in Rust

    impl Solution {
        fn reverse_number(n: i32) -> i32 {
            let mut num = n;
            let mut result = 0;
            while num > 0 {
                result = result * 10 + num % 10;
                num = num / 10;
            }
            result
        }
    }
    
    • Operator precedence. *, / and % bind tighter than +, so result * 10 + num % 10 means (result * 10) + (num % 10).
    • i32 range. Every input up to 1_000_000_000 reverses to a value that fits in an i32 (999_999_999 stays 999_999_999), so the lesson's inputs are safe. The largest i32 is 2,147,483,647.
    • Overflow wraps in an optimized build. The lessons build with -O, where integer overflow wraps silently. A debug build panics instead. With n = 1_999_999_999, whose reverse doesn't fit, an optimized build returns 1410065399 rather than an error. That input is outside the lesson's limits, but it shows why a reversal can need a wider type such as i64 in general.

    Tracing 120

    The trailing zero is the case people worry about, so here is the state after each pass for n = 120:

    passnum after the passresult after the pass
    1120
    212
    3021

    No special handling is needed: the leading zero of 021 simply never exists as a digit of an integer.

    Edge cases and common mistakes

    • Trailing zeros. 120 gives 21, and 1_000_000_000 gives 1.
    • Zero. The loop doesn't run, and the function returns 0.
    • One digit. 7 gives 7.
    • Swapping the two updates. If num is divided before num % 10 is used, the digit that was meant for result is already gone.
    • Forgetting the * 10. Just adding the digit gives the digit sum, not the reversal.

    Testing

    • n = 123 gives 321.
    • n = 120 gives 21.
    • n = 7 gives 7.
    • n = 0 gives 0.
    • n = 1000000000 gives 1.
    • n = 999999999 gives 999999999.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free