Start learning free

LESSON 218 OF 293 · WHILE LOOPS - CHALLENGES

Digit Sum in Rust: A while Loop with % and /

Practice Read the full explanation

Given a non-negative integer n, return the sum of its digits.

The digits are the figures from 0 to 9 that n is written with: 472 has the digits 4, 7 and 2. If n is 0, the sum is 0.

The last digit of a number is the remainder of its division by 10 (472 % 10 is 2), and dividing by 10 without the remainder removes that digit (472 becomes 47).

 

Example 1:

Input: n = 472
Output: 13
Explanation: Taking the digits from the right: 2 + 7 + 4 = 13.

Example 2:

Input: n = 1005
Output: 6
Explanation: 5 + 0 + 0 + 1 = 6. The zeros add nothing.

Example 3:

Input: n = 7
Output: 7
Explanation: A number with one digit is its own digit sum.

 

Constraints:

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

    RUST · WHILE LOOPS - CHALLENGES

    Digit Sum in Rust, explained

    Problem overview

    The function digit_sum takes a non-negative n and returns the sum of its digits. The input is at most 1_000_000_000, and digit_sum(0) is 0.

    For n = 472 the digits are 4, 7 and 2, and the sum is 13. For n = 1005 the sum is 6, because the zeros add nothing.

    Approach

    Integers don't give you their digits directly, but two operations do the job. n % 10 is the last digit, and n / 10 is the number without it. With two i32 values, / drops the remainder, so 472 / 10 is 47.

    So repeat: add the last digit to a running total, then drop it. When nothing is left, the number is 0 and every digit has been added. Here is 1005 as the loop sees it, with the state after each pass:

    passnum after the passtotal after the pass
    11005
    2105
    315
    406

    The zeros are visited like any other digit. They just add 0.

    Step by step

    1. Copy n into num with let mut. Parameters are immutable in Rust, and the loop has to change the number as it takes digits off.
    2. Create total, starting at 0. It is mutable because it grows. For n = 0 the loop never runs and 0 is the right answer.
    3. Loop while num > 0. Each pass removes one digit, so the loop runs once per digit.
    4. Add num % 10 to total with +=.
    5. Replace num with num / 10. Without this line num never changes and the loop never ends.
    6. Return total as the last expression, without a semicolon.

    The solution in Rust

    impl Solution {
        fn digit_sum(n: i32) -> i32 {
            let mut num = n;
            let mut total = 0;
            while num > 0 {
                total += num % 10;
                num = num / 10;
            }
            total
        }
    }
    
    • let mut. A plain let binding can't be reassigned. total += ... and num = ... both need mut.
    • Inferred types. total starts as a bare 0, and Rust makes it an i32 because the function returns i32 and num % 10 is one.
    • Integer division. Both operands are integers, so / drops the fractional part: 9 / 2 is 4, not 4.5. No cast is needed here.
    • The last expression. total has no semicolon, which makes it the return value.

    Why this works

    Every number is its last digit plus ten times the rest: 472 is 2 + 10 * 47. The remainder gives the first part, and the division gives the second. Repeating the split on the rest walks through every digit exactly once, from the right. Each division by 10 also shrinks the number, so a number below a billion needs at most ten passes.

    Edge cases and common mistakes

    • Zero. num > 0 is false at once, and the function returns 0.
    • The largest input. 1_000_000_000 gives 1, and 999_999_999 gives 81. The total is tiny compared with i32::MAX, so it can't overflow.
    • Forgetting the division. If num = num / 10 is missing, the loop adds the same last digit forever.
    • Looping on num != 0 with a negative input. Negative numbers aren't part of this lesson, and num > 0 keeps the loop from running for them: digit_sum(-5) would return 0.

    Testing

    • n = 472 gives 13.
    • n = 1005 gives 6.
    • n = 7 gives 7.
    • n = 0 gives 0.
    • n = 999999999 gives 81.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free