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.
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
:
countDigits(123456)
calls countDigits(12345)
and adds 1.countDigits(12345)
calls countDigits(1234)
and adds 1.countDigits(1234)
calls countDigits(123)
and adds 1.countDigits(123)
calls countDigits(12)
and adds 1.countDigits(12)
calls countDigits(1)
and adds 1.countDigits(1)
returns 1 as it is less than 10.countDigits(12)
adds 1 to the result of countDigits(1)
and returns 2.countDigits(123)
adds 1 to the result of countDigits(12)
and returns 3.countDigits(1234)
adds 1 to the result of countDigits(123)
and returns 4.countDigits(12345)
adds 1 to the result of countDigits(1234)
and returns 5.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.