【问题标题】:finding the largest digit in an integer using recursion使用递归找到整数中的最大数字
【发布时间】:2023-04-07 07:06:01
【问题描述】:

我有一个练习,他的任务是在 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);
}

如您所见,这是完全错误的。

任何帮助都会很棒。谢谢

【问题讨论】:

  • @Baadshah:我不明白为什么这个问题有必要。代码完全可读,没有。
  • 要改变的一件事是您返回的内容。您应该返回较大的 maxmaxDigit(n/10)
  • 这是家庭作业还是什么?我想不出一个更糟糕的地方来使用递归。
  • 您现在的代码将进入无限循环。没有从递归中出来。
  • @Assaf 在某些语言(即函数式语言)中递归将是解决此问题的自然方法。

标签: java recursion


【解决方案1】:

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

【讨论】:

  • 我认为 int 在 java 中不会计算为 truefalse
  • if (n) 不是有效的 java 语法
  • 哎呀-好点!我使用 JS 测试了算法,但没有在真正的 Java 编译器中测试语法。过失。
【解决方案2】:

最简单的基本情况,如果 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));
}

【讨论】:

  • 这在技术上与我的算法相同,尽管写法略有不同。
  • 哇。非常可爱!
【解决方案3】:

我不会深入研究您的代码,我认为它比它必须要复杂的多。但在我看来,这些案例实际上相当简单(除非我遗漏了什么):

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

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

【讨论】:

    【解决方案4】:

    你也可以写:

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

    【讨论】:

      猜你喜欢
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 2010-12-16
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多