2013-05-09 121 views
0

我有一个练习,其任务是使用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); 
} 

正如你可以看到它是完全错误的。

任何帮助将是伟大的。谢谢

+3

@Baadshah:我不明白为什么这个问题是必要的。代码是完全可读的没有。 – 2013-05-09 19:43:09

+0

有一件事要改变是你回报。你应该返回更大的'max'&'maxDigit(n/10)' – 2013-05-09 19:43:19

+0

这是一项家庭作业或什么?我想不出更糟糕的地方去使用递归。 – 2013-05-09 19:43:33

回答

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

这在技术上与我的算法相同,尽管写法略有不同。 – Alnitak 2013-05-09 19:54:59

+0

谢谢!它的工作 – Alan 2013-05-09 19:58:33

+0

awww。很可爱 ! – 2016-07-09 17:50:20

1

我不会深入你的代码,我认为它比它更复杂。但在我看来,该案件实际上是相当简单的(除非我失去了一些东西):

基本情况:参数只有一个数字,返回一个数字作为参数

一般情况下:返回取(参数中的第一个数字)和(参数中剩余数字的最大数字)的较高位数

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

如果(n)无效java语法 – A4L 2013-05-09 19:51:17

+0

!我使用JS测试了算法,但不是真正的Java编译器中的语法。 Mea culpa。 – user902383 2013-05-09 19:51:37

+0

oops - 好点!我不认为'int'在java中评估为'true'或'false' – Alnitak 2013-05-09 19:52:03