Problem overview
The function noOfDigits receives a non-negative integer n and returns how many digits it has. The number 542 has 3 digits and 100 has 3 too, since zeros count. The number 0 is written with one digit, so the answer for 0 is 1.
Approach
Dividing an Int by 10 with / drops the remainder and removes the last digit: 542 becomes 54, then 5, then 0. That takes three divisions, one per digit. So the plan is to count how many divisions it takes to reach 0.
The loop has one blind spot. It runs while the number is greater than 0, and 0 is not greater than 0, so for n = 0 it would count nothing and return 0. The right answer is 1, so that case is handled first, before the loop.
You could also convert the number to a String and take its count, which counts characters. The loop in this lesson stays with arithmetic, which is the skill the exercise practises. Both give the same answer for non-negative numbers.
Here is the count for 542, one division at a time: 542 becomes 54 (count 1), 54 becomes 5 (count 2), and 5 becomes 0 (count 3). Then num is 0 and the loop stops, with count holding 3. Seeing the count rise once per division makes it clear why the loop condition decides everything: it must stay true exactly as long as at least one digit remains.
Step by step
- Handle zero. If
n == 0, return 1 right away. - Copy
nintovar num. Parameters are constants in Swift, so the loop needs its own variable to change. - Create
var count = 0for the digits removed so far. - Loop while
num > 0. Each turn removes one digit. - Add 1 to
countwith+= 1. Swift has no++operator. - Replace
numwithnum / 10. - Return
countafter the loop.
The solution in Swift
class Solution {
func 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
}
}
Swift details worth knowing:
- No
++. Swift removed the increment operator. Writingcount++fails withcannot find operator '++' in scope; did you mean '+= 1'?. varandlet.numandcountchange, so they arevar. Assigning to the parameternwould fail withcannot assign to value: 'n' is a 'let' constant.- Integer division truncates.
Int / Intnever gives a fraction, so each division cleanly drops the last digit. - The early return. A
returninside anifends the function immediately, so the code after it only runs for numbers other than 0.
Edge cases and common mistakes
- Zero. Without the first
if,noOfDigits(0)would return 0. - Numbers ending in zeros.
100goes 100, 10, 1, 0, which is three divisions, so the answer is 3. - The largest input.
1000000000has 10 digits, and the loop runs 10 times. - Forgetting to shrink
num. If the loop never divides, it never ends. - Counting after the loop with a wrong starting value. Starting
countat 1 would be off by one for every number except 0, which is handled separately.
Testing
542gives 3.100gives 3.0gives 1.7gives 1.1000000000gives 10.
