How many digits
EasyStuck?
Show a hintHide the hint
Strip a digit at a time with division by ten, counting each one. Zero has one digit and the loop will not see it.
The ideas behind this problem
Next in this lesson
Turn the digits aroundCount the digits in a whole number.
Worked example#
For 4071, strip one digit off the right at a time and count as you go:
| n | last digit | n after removing it | counted so far |
|---|---|---|---|
| 4071 | 1 | 407 | 1 |
| 407 | 7 | 40 | 2 |
| 40 | 0 | 4 | 3 |
| 4 | 4 | 0 | 4 |
Nothing is left, so the answer is 4.
The two operations#
n % 10 is the last digit. n / 10 removes it, as long as the division throws the fraction away.
count = 0
while n > 0:
count = count + 1
n = n / 10
In Python you must write n // 10. Plain / gives 40.7 instead of 40, the loop never reaches zero, and it runs for ever. In C, C++ and Java integer division already discards the fraction.
The case that catches everyone#
Zero. The loop never runs, so the count comes out as 0. But 0 is written with one digit, so the answer should be 1. Handle it before the loop.
Counting the characters in the number written as text also works, and for 0 it happens to be right. It is slower and uses more memory, and it is a perfectly reasonable answer when clarity matters more than either.
Constraints#
0 <= n <= 1000000000
Input
n is one whole number.
Output
The number of digits.
Examples
Input
4071
Output
4
Four digits come off before nothing is left.
Input
0
Output
1
Zero is written with one digit, and the loop never runs for it.
Input
7
Output
1
A single digit.
Something wrong with this problem? Report an issue
Ready to try it
Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.
Free, and it stays free. No card.