Post

Created by @nathanedwards
 at November 1st 2023, 7:44:57 pm.

Question:

Write a recursive method in Java called countDigits that takes an integer num as its parameter and returns the number of digits in num. You may assume that num will always be a non-negative integer.

Signature:

public static int countDigits(int num)

Example:

countDigits(12345)  // returns 5
countDigits(7)      // returns 1
countDigits(987654321)  // returns 9

Explanation:

To solve this problem recursively, we can break it down into smaller sub-problems.

The base case would be when num is less than 10. In this case, the number of digits is 1 since there is only a single digit in num.

For numbers greater than or equal to 10, we can call the countDigits method recursively on num/10 (i.e., without its last digit) and add 1 to the result.

Here is the step-by-step explanation of the countDigits method:

  1. If num is less than 10, return 1 as the number of digits.
  2. Otherwise, recursively call countDigits on num/10 and add 1 to the result.

Using these steps, we can implement the countDigits method as follows:

Solution:

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

Now, let's test the method with the provided examples:

System.out.println(countDigits(12345));      // Output: 5
System.out.println(countDigits(7));          // Output: 1
System.out.println(countDigits(987654321));  // Output: 9

The method countDigits correctly returns the number of digits in a given number by utilizing recursion.