Alan Alan - 5 months ago 37
Java Question

finding the largest digit in an integer using recursion

I have a practice who's task is to find the largest digit in an integer using recursion in java. For example, for the number 13441 the digit '4' will be returned.

I have been trying for a day now and nothing worked.

What I thought could work is the following code, which I can't quite get the "base case" for:

public static int maxDigit(int n) {
int max;
if (n/100==0) {
if (n%10>(n/10)%10) {
max=n%10;
}
else
max=(n/10)%10;
}
else if (n%10>n%100)
max=n%10;
else
max=n%100;
return maxDigit(n/10);
}


As you can see it's completely wrong.

Any help would be great. Thank you

Answer

The simplest base case, is that if n is 0, return 0.

public static int maxDigit(int n){
    if(n==0)                               // Base case: if n==0, return 0
        return 0;
    return Math.max(n%10, maxDigit(n/10)); // Return max of current digit and 
                                           // maxDigit of the rest 
}

or, slightly more concise;

public static int maxDigit(int n){
    return n==0 ? 0 : Math.max(n%10, maxDigit(n/10));
}