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?

+3


source to share


4 answers


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);
}

      

+4


source


static int getGreatestDigit(int num)
{
    return num == 0 ? 0 :
        Math.Max(num % 10, getGreatestDigit(num / 10));
}

      



So basically, you look at the least significant digit each time, comparing it to the maximum number of the remaining digits.

+3


source


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;
  }
 }
}

      

+1


source


/** Pseudocode:
1. if num > 9, /10 and call getGreatestDigit on that (recursive step). Then get the current digit (undivided) and return the greater of the two
2. if num <= 9, return num
*/

int getGreatestDigit(int num){
 //code
}

      

0


source







All Articles