Post

Created by @nathanedwards
 at November 2nd 2023, 7:44:51 am.

Question:

/**
 * You are given the following recursive method signature:

 * public static int countDigits(int number)

 * The method takes an integer number and returns the count of its digits. 

 * Write a recursive implementation of the method countDigits.
 */

public class RecursiveMethods {
    
    public static int countDigits(int number) {
        // Your code here
        
    }

    public static void main(String[] args) {
        int testNumber = 123456;
        System.out.println("Number of digits in " + testNumber + " is: " + countDigits(testNumber));
    }
}

Answer:

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

    public static void main(String[] args) {
        int testNumber = 123456;
        System.out.println("Number of digits in " + testNumber + " is: " + countDigits(testNumber));
    }
}

Explanation:

The given problem requires us to count the number of digits in a given integer using a recursive method.

To solve this problem recursively, we need to consider the base case and the recursive case.

  • Base Case: If the number is less than 10 (i.e., it is a single digit number), we can simply return 1, as it has only one digit.
  • Recursive Case: For numbers greater than or equal to 10, we can use integer division by 10 (number / 10) to remove the last digit. Then, we recursively call the countDigits method on the remaining number and add 1 to the result to account for the removed digit.

Let's take an example and trace the execution of the recursive calls:

For testNumber = 123456:

  1. countDigits(123456) calls countDigits(12345) and adds 1.
  2. countDigits(12345) calls countDigits(1234) and adds 1.
  3. countDigits(1234) calls countDigits(123) and adds 1.
  4. countDigits(123) calls countDigits(12) and adds 1.
  5. countDigits(12) calls countDigits(1) and adds 1.
  6. countDigits(1) returns 1 as it is less than 10.
  7. countDigits(12) adds 1 to the result of countDigits(1) and returns 2.
  8. countDigits(123) adds 1 to the result of countDigits(12) and returns 3.
  9. countDigits(1234) adds 1 to the result of countDigits(123) and returns 4.
  10. countDigits(12345) adds 1 to the result of countDigits(1234) and returns 5.
  11. countDigits(123456) adds 1 to the result of countDigits(12345) and returns 6.

Finally, the output will be:

Number of digits in 123456 is: 6

The recursive implementation correctly counts the number of digits in the given integer.