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:
num is less than 10, return 1 as the number of digits.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.