使用递归查找整数中的最大数字

时间:2013-05-09 19:39:12

标签: java recursion

我有一个练习,他的任务是使用java中的递归来查找整数中的最大数字。例如,对于数字13441,将返回数字“4”。

我一直在尝试一天,没有任何效果。

我认为可以使用的是以下代码,我不能完全得到“基本情况”:

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

正如你所看到的,这是完全错误的。

任何帮助都会很棒。谢谢

4 个答案:

答案 0 :(得分:7)

这可以通过递归地比较最右边的数字和剩余数字的最高位数(通过将原始数字除以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;
    } 
}

答案 1 :(得分:6)

最简单的基本情况是,如果n为0,则返回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 
}

或者,更简洁;

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

答案 2 :(得分:1)

我不会深入研究你的代码,我觉得它比以前更复杂。但在我看来,案件实际上相当简单(除非我遗漏了一些东西):

基本情况:参数只有一位数,返回那一位作为参数

一般情况:返回(参数中的第一个数字)和(参数中剩余数字的maxDigit)中的较高者。

答案 3 :(得分:0)

你也可以写:

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;
}
相关问题