Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Count Digits Recursively

Count integer digits using recursive floor division. Students trace one count per decimal position and separate zero input from the helper's empty remainder.

IntermediatePhase 3 - Level 2: Advanced RecursionExample 1 of 10
count-digits-recursively.py
1def count_digits(n):
2 # Base case
3 if n == 0:
4 return 0
5
6 # Recursive case
7 return 1 + count_digits(n // 10)
8
9# Test
10num = int(input("Enter a number: "))
11result = 1 if num == 0 else count_digits(abs(num))
12print(f"Number of digits: {result}")

Output

Enter a number: 12345
Number of digits: 5

In this one

  • Count one digit per call
  • Separate zero from exhaustion
  • Preserve a neutral base case

How it works

  1. 1

    Choose one directly for literal input zero.

  2. 2

    Otherwise call the helper on abs(num).

  3. 3

    Return one plus the smaller digit count until exhaustion.

Edge cases

How many digits should input zero report?

How many digits should input zero report?

One, handled outside the empty-remainder base case.

Why not make every terminal return one?

Why not make every terminal return one?

That would add an extra position to nonzero numbers.

What's going on

The helper returns zero when no positive positions remain. Otherwise it counts one position and requests the count of n // 10.

For 405, the returns combine into three. The outer zero input needs its own one-digit result; changing the helper's terminal value would overcount every other input. abs removes a sign before the recursive calls occupy the call stack.

How many digits should input zero report? One, handled outside the empty-remainder base case.

Why not make every terminal return one? That would add an extra position to nonzero numbers.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does the recursive step add?

Pick an answer to check it.

Question 2

How many digits should input zero report?

Pick an answer to check it.

Questions people ask

How many digits should input zero report?

One, handled outside the empty-remainder base case.

Why not make every terminal return one?

That would add an extra position to nonzero numbers.

What does the recursive step add?

One digit.