Problem overview
The function noOfDigits takes a non-negative Int, n, and returns how many digits it is written with. For 542 the answer is 3. For 100 it is 3 too, because the zeros are digits. The number 0 is written with one digit, so noOfDigits(0) is 1.
Approach
Dividing an Int by 10 with / drops the last digit: 542 becomes 54, then 5, then 0. The number of divisions needed to reach 0 is the number of digits. So the plan is a loop that divides by 10 and counts each division.
The loop has one weak spot. It runs only while the number is greater than 0, so for n = 0 it would run zero times and report no digits, but 0 has one. That single input is handled before the loop.
Step by step
- If
nis 0, return 1 right away. - Copy
nintovar num. The parameter itself is immutable in Scala, so the loop works on the copy. - Create
var count, starting at 0. It counts the digits removed so far. - Write a
whileloop that runs whilenum > 0. - Inside the loop, add 1 to
countwithcount += 1. Scala has no++operator. - Still inside, set
numtonum / 10. - After the loop, return
count.
For n = 542 the loop runs like this:
| Turn | num after the turn | count after the turn |
|---|---|---|
| 1 | 54 | 1 |
| 2 | 5 | 2 |
| 3 | 0 | 3 |
Why zero needs its own case
The loop condition num > 0 asks "is there still a digit to remove?". For every positive number the answer is yes until the last digit is gone. For 0 the condition is false from the start, so the loop would count nothing, yet 0 is written with one digit. Special cases like this are worth spotting early: before trusting a loop, try it on the smallest input it must accept. The explicit if keeps the main loop simple instead of bending it to fit one value.
The solution in Scala
class Solution {
def noOfDigits(n: Int): Int = {
if (n == 0) {
return 1
}
var num = n
var count = 0
while (num > 0) {
count += 1
num = num / 10
}
return count
}
}
Details that matter in Scala:
- A
returninside theifleaves the method at once, so the code below it runs only for non-zero numbers. num / 10is integer division because both sides areInt. The remainder is thrown away, which is exactly the "drop the last digit" operation.count += 1is the way to increment, since++doesn't exist for numbers in Scala.- The largest input, 1000000000, has 10 digits, and the loop runs 10 times. The count stays tiny compared with the limits of
Int.
Edge cases and common mistakes
- Zero. Without the first
if, the answer for 0 would be 0. With it, the answer is 1. - Zeros inside or at the end. 100 becomes 10, then 1, then 0: three turns, so 3 digits. The zeros are counted like any other digit.
- Single digits. 7 gives 1: one division takes it to 0.
- Counting inside the wrong place. Putting
return countinside the loop ends it after the first digit.
Testing
noOfDigits(542) -> 3
noOfDigits(100) -> 3
noOfDigits(0) -> 1
noOfDigits(7) -> 1
noOfDigits(1000000000) -> 10
