Assaf
Assaf

Reputation: 1124

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

Upvotes: 0

Views: 15982

Answers (5)

This is the solution.

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

Upvotes: 0

user1606259
user1606259

Reputation: 1

You may also write:

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

Upvotes: 0

Alnitak
Alnitak

Reputation: 339796

This works by recursively comparing the right most digit with the highest digit of the remaining digits (those being obtained by dividing the original number by 10):

int maxDigit(int n) {
    n = Math.abs(n);   // make sure n is positive
    if (n > 0) {
        int digit = n % 10;
        int max = maxDigit(n / 10);
        return Math.max(digit, max);
    } else {
        return 0;
    } 
}

Upvotes: 7

Joachim Isaksson
Joachim Isaksson

Reputation: 180897

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

Upvotes: 7

Jacob Mattison
Jacob Mattison

Reputation: 51052

I won't dig into your code, which I think is more complicated than it has to be. But it seems to me that the cases are actually fairly simple (unless I'm missing something):

base case: parameter only has one digit, return that one digit as parameter

general case: return whichever is higher of (the first digit in the parameter) and (the maxDigit of the remaining digits in the parameter)

Upvotes: 1

Related Questions