Problem overview
NoOfDigits receives a non-negative int n and returns how many digits it has. 542 has 3, 100 has 3 (zeros are digits too) and 0 has 1.
Approach
Dividing an int by 10 with / drops the last digit, because integer division truncates: 542 / 10 is 54. So the number of digits is the number of times you can divide by 10 before reaching 0. For 542 that goes 542, 54, 5, 0: three divisions.
The number 0 is the one case that breaks this. It has one digit, but it is already 0, so a loop that runs while n > 0 would run zero times and answer 0. The lesson handles it first, with its own if.
Step by step
- If
nis 0, return 1. This is the special case. - Create
countas anintset to 0. It counts the digits removed so far. - Write
while (n > 0). Each pass removes one digit. - Add 1 to
countwith++. One pass is one digit. - Divide
nby 10 and store the result back inn. - Return
countafter the loop.
For n = 542:
| Pass | count | n after dividing |
|---|---|---|
| 1 | 1 | 54 |
| 2 | 2 | 5 |
| 3 | 3 | 0 |
The solution in C#
class Solution {
public int NoOfDigits(int n) {
if (n == 0) {
return 1;
}
int count = 0;
while (n > 0) {
count++;
n = n / 10;
}
return count;
}
}
The early return ends the method at once, so the loop code is only reached for numbers above 0. The loop never reads the digits themselves. It only counts how many times it can divide, so a 0 inside the number, as in 100, is counted like any other digit.
An alternative: do-while
C# has a loop that runs its body once before it tests the condition: do { ... } while (condition);. With it, the special case for 0 is no longer needed, because one pass always happens and counts the single digit of 0:
int count = 0;
do {
count++;
n = n / 10;
} while (n > 0);
This gives 1 for 0, 3 for 542 and 3 for 100. The lesson uses the early return and a plain while, which is the form you will meet in most code, but both are correct.
Why dividing by 10 counts digits
In base 10, every digit is worth ten times the one on its right. Dividing by 10 and dropping the remainder shifts the whole number one place to the right, so the last digit falls off. A number with d digits can be shifted d times before nothing is left. That is why the loop count equals the digit count.
The loop only needs the size of n, not its digits, so it does not use % at all. Compare it with a digit sum, where n % 10 is needed to read each digit before removing it.
Edge cases and common mistakes
- Zero. Without the first
if,NoOfDigits(0)would return 0. - Trailing zeros.
100goes 100, 10, 1, 0, which is three passes. The answer is 3. - Largest input.
1000000000has 10 digits, and the loop returns 10. It fits easily in anint. - Forgetting the division. If
nis never changed, the loop never ends.
Testing
The solution returns 3 for 542, 3 for 100, 1 for 0 and 10 for 1000000000.
