How can I find the largest digit in a number using recursion?
I am trying to write a function in Java that returns the largest digit in a number using recursion. I was able to do this using two parameters: a number and a digit. Initially, the most significant parameter of the digit is set to 0.
static int getGreatestDigit(int num , int greater){
if(num != 0){
if(num %10 > greater){
greater = num%10;
num = num/10;
return getGreatestDigit(num , greater);
}else{
num = num/10;
return getGreatestDigit(num , greater);
}
}
return greater;
}
I want to write the same recursive function but with only one parameter, which is a number. how
int getGreatestDigit(int num){
//code
}
I get hung up on logic. How to do it?
source to share
Only the first call getGreatestDigit(num)
should track the result greater
. Each recursive call getGreatestDigit(num)
returns the largest digit in the part of the original number assigned to scan. The very first call getGreatestDigit(num)
can compare the number it took with the largest number returned from all recursive calls.
int getGreatestDigit(int num)
{
if (num == 0) return 0;
int lastNum = num % 10;
int otherDigits = num / 10;
int recursiveLastNum = getGreatestDigit(otherDigits);
return Math.Max(lastNum, recursiveLastNum);
}
source to share
This can be done if you use the function stack as temporary memory to store intermediate results, that is, previously stored in a parameter greater
.
This changes your function to not be tail-recursive, which degrades its performance.
int greatestDigit(int num) {
int last = num % 10;
int rest = num / 10;
if (rest == 0) {
return last;
} else {
int candidate = greatestDigit (rest);
if (candidate > last) {
return candidate;
} else {
return last;
}
}
}
source to share