Problem overview
The function no_of_digits takes a non-negative n, at most 1_000_000_000, and returns how many digits it has. The number 0 has one digit.
For n = 542 the answer is 3. For n = 100 it is also 3: the zeros are digits too.
Approach
Dividing an integer by 10 removes its last digit: 542 / 10 is 54. If you count how many divisions it takes to reach 0, you have counted the digits.
For 542 the loop runs three times:
| pass | num after the pass | count after the pass |
|---|---|---|
| 1 | 54 | 1 |
| 2 | 5 | 2 |
| 3 | 0 | 3 |
There is one number the loop gets wrong. For 0 the condition num > 0 is false from the start, so the loop would count no digits, yet 0 is written with one. A check at the top handles it.
Step by step
- Return 1 when
nis 0. This is the only input the loop can't count. - Copy
nintonumwithlet mut. Function parameters are immutable, so the loop needs its own variable to change. - Create
countat 0. It counts the digits removed so far. - Loop while
num > 0. One pass is one digit. - Add 1 to
countwith+= 1. Rust has no++operator. - Replace
numwithnum / 10to drop the last digit. - Return
countas the last expression.
The solution in Rust
impl Solution {
fn no_of_digits(n: i32) -> i32 {
if n == 0 {
return 1;
}
let mut num = n;
let mut count = 0;
while num > 0 {
count += 1;
num = num / 10;
}
count
}
}
- Early
return. Inside theifblock,return 1;leaves the function at once. The final line,count, is the value for every other path. - No
++. Rust spells itcount += 1. - Integer division. Two
i32operands make/an integer division, so542 / 10is 54 and not 54.2.
Why the loop is enough
A number with d digits becomes a number with d - 1 digits after one division by 10, and a one-digit number becomes 0. So the number of divisions needed to reach 0 is exactly d, for every positive n. That argument fails for 0 only because 0 is already at the target before the first division, which is the reason for the special case.
The same idea can be written without a loop, by converting the number to text and taking its length, but the lesson practises the arithmetic version, which works on the number itself.
Digits that are zeros need no special care. For 100 the loop divides to 10, then 1, then 0, and counts three passes, just as it does for 542.
Edge cases and common mistakes
- Zero. Without the early return,
no_of_digits(0)would give 0, because the loop body never runs. - Trailing zeros.
100gives 3 and1_000_000_000, the largest input, gives 10. - One digit.
7gives 1: one pass takes it to 0. - Counting after the division. The order of the two statements inside the loop doesn't change the result, since the condition is only checked at the top of each pass.
Testing
n = 542gives 3.n = 100gives 3.n = 0gives 1.n = 7gives 1.n = 1000000000gives 10.
