Count Digits Using Recursion

Count Digits Using Recursion

Hard C++ Functions 43 views
Explanation Complexity

Problem Statement

Count number of digits in a number using recursive function.
Real Life: Understanding number structure recursively.

Input Format

An integer N.

Output Format

Number of digits in N.

Example

12345
5

Constraints

• N ≥ 0

• Use recursion only

Concept Explanation

Digits are counted by repeatedly removing the last digit.
Recursion helps break the number into smaller parts.

Step-by-Step Explanation

1.If N is less than 10:

• It has only 1 digit (base case).

2.Otherwise:

• Remove the last digit using N / 10.

3.Call the function again with the smaller number.

4.Add 1 for the current digit.

5.Continue until base case is reached.

6.Final count is returned.

Concept Explanation

Digits are counted by repeatedly removing the last digit.
Recursion helps break the number into smaller parts.

Step-by-Step Explanation

1.If N is less than 10:

• It has only 1 digit (base case).

2.Otherwise:

• Remove the last digit using N / 10.

3.Call the function again with the smaller number.

4.Add 1 for the current digit.

5.Continue until base case is reached.

6.Final count is returned.

Input / Output Format

Input Format
An integer N.
Output Format
Number of digits in N.
Constraints
• N ≥ 0

• Use recursion only

Examples

Input:
12345
Output:
5

Example Solution (Public)

C++
int countDigits(int num) {
    if(num == 0) {
        return 0;  // Base case
    }
    return 1 + countDigits(num / 10);  // Recursive call
}

void function_q15_count_digits() {
    int number = 12345;
    
    if(number == 0) {
        cout << "Number of digits: 1" << endl;
    } else {
        int digits = countDigits(number);
        cout << "Number of digits in " << number << " is: " << digits << endl;
    }
}

Official Solution Code

int countDigits(int num) {
    if(num == 0) {
        return 0;  // Base case
    }
    return 1 + countDigits(num / 10);  // Recursive call
}

void function_q15_count_digits() {
    int number = 12345;
    
    if(number == 0) {
        cout << "Number of digits: 1" << endl;
    } else {
        int digits = countDigits(number);
        cout << "Number of digits in " << number << " is: " << digits << endl;
    }
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.