This problem follows the same structure as sum of digits, but you count instead of adding.
Base case: When , you have a single digit. A single-digit number has exactly digit.
def count_digits(n):
if n < 10:
return 1
return 1 + count_digits(n // 10)
Tracing count_digits(123):
count_digits(123) = 1 + count_digits(12)
count_digits(12) = 1 + count_digits(1)
count_digits(1) = 1 <- Base case
Working back: . Each division by removes one digit and adds to the count.