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:
| pass | num after the pass | total after the pass |
|---|---|---|
| 1 | 100 | 5 |
| 2 | 10 | 5 |
| 3 | 1 | 5 |
| 4 | 0 | 6 |
The zeros are visited like any other digit. They just add 0.
Step by step
- Copy
nintonumwithlet mut. Parameters are immutable in Rust, and the loop has to change the number as it takes digits off. - Create
total, starting at 0. It is mutable because it grows. Forn = 0the loop never runs and 0 is the right answer. - Loop while
num > 0. Each pass removes one digit, so the loop runs once per digit. - Add
num % 10tototalwith+=. - Replace
numwithnum / 10. Without this linenumnever changes and the loop never ends. - Return
totalas 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 plainletbinding can't be reassigned.total += ...andnum = ...both needmut.- Inferred types.
totalstarts as a bare0, and Rust makes it ani32because the function returnsi32andnum % 10is one. - Integer division. Both operands are integers, so
/drops the fractional part:9 / 2is 4, not 4.5. No cast is needed here. - The last expression.
totalhas 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 > 0is false at once, and the function returns 0. - The largest input.
1_000_000_000gives 1, and999_999_999gives 81. The total is tiny compared withi32::MAX, so it can't overflow. - Forgetting the division. If
num = num / 10is missing, the loop adds the same last digit forever. - Looping on
num != 0with a negative input. Negative numbers aren't part of this lesson, andnum > 0keeps the loop from running for them:digit_sum(-5)would return 0.
Testing
n = 472gives 13.n = 1005gives 6.n = 7gives 7.n = 0gives 0.n = 999999999gives 81.
