Count Digits Using Recursion
C++
Hard
4 views
Problem Description
Count number of digits in a number using recursive function.
Real Life: Understanding number structure recursively.
Step-by-Step Logic:
1. Base case: if number is 0, return 0
2. Remove last digit (divide by 10)
3. Recursively count digits in remaining number
4. Add 1 for current digit
5. Return total count
Official Solution
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;
}
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!