Problem overview
The function noOfDigits receives a non-negative integer n and returns how many digits it is written with. 542 has 3, 100 has 3 (the zeros are digits too), and 0 has 1.
Approach
Integer division by 10 removes the last digit: 542 / 10 is 54, then 5, then 0. The number of divisions needed to reach 0 is the number of digits, so a loop can count them.
Printing the values after each pass for 542 shows it:
| Pass | num after | count after |
|---|---|---|
| 1 | 54 | 1 |
| 2 | 5 | 2 |
| 3 | 0 | 3 |
The loop has one blind spot. It runs only while the number is above 0, and 0 is already 0, so it would count no digits at all for it. But 0 is written with one digit, so that case gets its own answer first.
Step by step
- Handle zero. If
n == 0, return 1 right away. - Copy
nintonumwithvar, because parameters are read-only and the loop must change the value. - Start
countat 0. No digit has been removed yet. - Loop while
num > 0. Every pass removes one digit. - Count it with
count++. - Drop the last digit by storing
num / 10back innum. - Return
count.
The solution in Kotlin
class Solution {
fun noOfDigits(n: Int): Int {
if (n == 0) {
return 1
}
var num = n
var count = 0
while (num > 0) {
count++
num = num / 10
}
return count
}
}
Some details worth knowing:
count++adds 1 to avar. It is shorthand forcount += 1.- Integer division. With two
Intvalues,/drops the remainder, so5 / 10is 0 and the loop ends after the last digit. - The largest input.
1000000000fits in anIntand has 10 digits, which the function returns.
Another way: through a string
Kotlin can also turn the number into text and measure it. 1000000000.toString().length is 10, which agrees with the loop. That is shorter, but it builds a string only to throw it away, and it hides the idea this lesson practises: each division by 10 removes one digit. The loop version also carries over to bases other than 10, where you divide by the base instead.
Why zero needs its own case
A loop that starts with while (num > 0) asks "is there a digit to remove?" For every positive number the answer is yes at least once, but for 0 it is no from the start, even though the number is written with a digit. Checking n == 0 first keeps the loop simple. Moving the check into the loop, for example with a do { ... } while form, also works, but the early return is easier to read.
Complexity
Time is O(d) for a number with d digits: one pass per digit. Space is O(1).
Edge cases and common mistakes
- Zero. Without the early return the function would give 0 instead of 1.
- Numbers ending in zeros.
100goes 100, 10, 1, 0 and counts 3. - Forgetting to shrink
num. The loop would never end. - Returning inside the loop. Return after it, once every digit is counted.
Testing
542gives3.100gives3.0gives1.1000000000gives10.
