Count all Digits of a Number
EasyDivide by 10 until nothing is left
Problem
Given a non-negative integer n, count how many digits it has.
Keep chopping off the last digit until nothing is left, counting each chop.
The idea
Repeatedly divide by 10, counting each division. Each one strips the last digit, so the number of divisions before reaching zero is the number of digits — which is why the loop runs about log₁₀(n) times rather than n times.
The trick
- Guard n == 0 explicitly: the loop would report 0 digits, but the answer is 1.
- You can also do it in O(1) with floor(log10(n)) + 1, mind the same zero case.
7
7
8
9
0
1
2
3
count0
Step 1 of 6. Count the digits of 7789. Values: 7, 7, 8, 9. count 0.
1/6
Optimal
timeO(log n)spaceO(1)
1count = 02if n == 0: return 13while n > 0:4 n = n / 10 // remove the last digit5 count++6return countInput
- array
- [7, 7, 8, 9]
Memory
- •
- —
- left
- —
Output
- count
- 0
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- n = 7
- Output:
- 1
- Explanation:
- 7 is a single digit, so the count is 1.
Example 2
- Input:
- n = 328
- Output:
- 3
- Explanation:
- The digits are 3, 2 and 8 — that is 3 digits.
Example 3
- Input:
- n = 100000
- Output:
- 6
- Explanation:
- 1 followed by five 0s makes 6 digits.
Example 4
- Input:
- n = 0
- Output:
- 1
- Explanation:
- 0 itself counts as one digit.
Practice this problem:GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.