Lesson 3.3 · Write it
Count the digits
A functionPython or Java9 tests, 6 of them hidden
On a phone? Put the lines in order instead
Write a function that returns how many digits a whole number has, using a loop that keeps going while there are digits left to count.
nis a whole number from 0 up to 2147483647.- 0 has one digit.
- Do not turn the number into text in any way (including f-strings in Python or
"" + nin Java), and do not use logarithms. The shortcuts listed with this question are not allowed.
Only the number your function returns is checked.
def digit_count(n: int) -> int
You cannot use these in this question:
- str()
- len()
- repr()
- format()
- ascii()
- .format()
- .__str__()
- .__repr__()
- .__format__()
- import math
- import decimal
- import cmath
This question is about writing a loop that stops at the right time, so turning the number into text or using logarithms is not allowed.
Examples
Your function is tested on 9 cases: the 3 examples below, and 6 hidden ones that check the rules above.
- digit_count(472) should return 3: three digits
- digit_count(0) should return 1: zero has one digit (rule 2)
- digit_count(10) should return 2: the smallest number with two digits
public static int digitCount(int n)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.Checking whether Java answers can run here.
You cannot use these in this question:
- String.valueOf()
- Integer.toString()
- Long.toString()
- String.format()
- Integer.toUnsignedString()
- Math.log10()
- Math.log()
- .length()
- .toCharArray()
- .chars()
- .codePoints()
- .split()
- .getBytes()
- .charAt()
- .toString()
- .precision()
- .indexOf()
- import java.math
This question is about writing a loop that stops at the right time, so turning the number into text or using logarithms is not allowed.
Examples
Your function is tested on 9 cases: the 3 examples below, and 6 hidden ones that check the rules above.
- digitCount(472) should return 3: three digits
- digitCount(0) should return 1: zero has one digit (rule 2)
- digitCount(10) should return 2: the smallest number with two digits