I want to write a recursive method that receives a number and a digit. The method should return a second number consisting of only the digits of the first parameter which are divisible by the second parameter.
For example, if the method is called with number = 5369405 and digit = 5, then it should return 505.
So far, I've written the following method but it doesn't work as the index remains at -1 and I'd like to save its value during each recursion. My idea was to save the values to construct the returned number.
Can anyone tell me how I can save the index during every recursion to prevent it from returning -1?
This is the code I've written:
public static int subNumber(int num, int digit)
{
int index=-1;
if(num <10)
{
if(num%digit==0){
index ;
return num*(int)Math.pow(10,index);
}
else{
return 0;
}
}
int mod=(num);
if(mod % digit ==0)
{
index ;
return mod*(int)Math.pow(10,index) subNumber(num/10,digit);
}
else{
return 0 subNumber(num/10,digit);
}
}
CodePudding user response:
As @markspace has suggested in the comments, you should also pass an index to your method to keep track of the position of every divisible digit in order to properly compute their weight within the final number.
Also, when designing a recursive method you should firstly identify your base cases. In this scenario, your base cases are:
The number passed is smaller than the digit to divide with.
The number passed is equal to the digit to divide with.
Additionally, the user could pass an inconsistent index (anything but zero). Usually in these cases, when the user is supposed to pass parameters that are only meant to help you with your recursive computation, you should hide the actual recursive method and only offer a client version of it. Basically, this client version only makes a call to the proper recursive method with the right parameters in order to avoid misuses.
One Method Solution
public static int subNumber(int num, int digit, int index) {
//Base case where num is smaller than than the digit to divide with
if (num < digit) {
return 0;
}
//Base case where num corresponds to digit and therefore is divisible
if (num == digit) {
return num * ((int) Math.pow(10, index));
}
//Retrieving the less significant digit
int modDigit = (num % 10);
//If the current mod digit is divisible by digit then its i-th position is defined and the later call results are added to it
if (modDigit % digit == 0) {
return modDigit * ((int) Math.pow(10, index)) subNumber(num / 10, digit, index 1);
}
//Proceeding with the recursion without adding a value to sum (conceptually should be return 0 subNumber(...))
return subNumber(num / 10, digit, index);
}
Client Method Solution
public static int subNumberClient(int num, int digit){
return subNumber(num, digit, 0);
}
private static int subNumber(int num, int digit, int index) {
//same implementation but with private access modifier
}