Problem overview
The function noOfDigits receives a non-negative integer n and returns how many digits it is written with. The number 542 has 3 digits and 100 has 3, because zeros count. The number 0 is written with one digit, so the answer for it is 1.
Approach
Dividing by 10 with integer division 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 the plan is to divide in a loop and count the turns.
There is one number the loop can't handle. The loop runs only while n is greater than 0, so for n = 0 it would run zero times and report 0 digits, when the right answer is 1. The function therefore handles 0 first, before the loop.
Step by step
- Return 1 if
nis 0. This is the one case the loop would get wrong. - Start
countat 0. No digit has been removed yet. - Loop while
n > 0. Each turn removes one digit. - Add 1 to
countinside the loop: one turn is one digit. - Set
nton // 10. The last digit is dropped, and eventuallynis 0 and the loop stops. - Return
countafter the loop.
The solution in Python
class Solution:
def noOfDigits(self, n: int) -> int:
if n == 0:
return 1
count = 0
while n > 0:
count += 1
n = n // 10
return count
Details worth knowing:
- Early return. A
returninside theifends the function at once, so the code after it runs only for numbers other than 0. //keeps the whole part.542 // 10is 54. The slash/would give the float 54.2, which never reaches 0 in a useful way.- Large values. Python integers don't overflow, so
1000000000works and returns 10. - The string shortcut.
len(str(542))is also 3. The loop shows the arithmetic behind it.
Why the zero check is needed
Here is what the loop alone does. Without the first if, a function that only counts turns returns 0 for n = 0 and 1 for n = 5. The second answer is right, the first is not: 0 is written with a digit, even though dividing it by 10 has nothing left to remove. The lesson treats the zero as a special case instead of changing the loop.
On 542 the loop sees n equal to 542, then 54, then 5, and counts three turns before n becomes 0. The loop runs once for each digit, so the answer is exactly the number of divisions.
Edge cases and common mistakes
- Zero. Without the first check the function would return 0 for
n = 0. - Trailing zeros.
100goes 100, 10, 1, 0 in three divisions, so it returns 3. - Single digits.
7becomes 0 after one division, so the answer is 1. - Counting after the loop. Putting
count += 1outside the loop gives a result of 1 for every positive number. - A missing division. If
n = n // 10is left out,nstays positive forever and the program never finishes.
Testing
542gives3.100gives3.0gives1.7gives1.1000000000gives10.
