educative.io

Recursive code snippet seems to have a bug

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

Hi @Sandeep_Sankranti !!
Your suggestion is correct for all cases but If the input number is 0, the answer is 0, even though it should be 1. The correct base case for recursive solution is

 public static int countDigits(int num) {
      if (num < 10) {
        return 1;
      }
      else {
        return 1 + countDigits(num/10);
      }
    }

and for iterative solution is:

  public static int countDigits(int num) {
      int count = 1;
      while (num >= 10) {
        num = num / 10;
        count++;
      }
      return count;
    }

This will also be updated in the course shortly.
Thanks!!

1 Like

Hi @Sandeep_Sankranti !!
We have updated the codes in the course.:partying_face:
Happy Learning :blush:

1 Like