2013-05-09 127 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