The base case for the recursion is wrong. If we give a single digit number, it prints the output as 2.
The method with the base case should be:
public static int countDigits(int num) {
if (num == 0) {
return 0;
}
else {
return 1 + countDigits(num/10);
}
}
Course: Recursion for Coding Interviews in Java - Learn Interactively
Lesson: Changing Iterative Code to Recursive - Recursion for Coding Interviews in Java