2011-03-08 83 views
0

我試圖把一個整數作爲參數,然後使用遞歸將整數中的每個數字加倍。Java遞歸和整數雙位數字

例如doubleDigit(3487)將返回33448877

我被卡住了,因爲我無法弄清楚如何讀取數字中的每個數字。

+3

不知道爲什麼你想使用遞歸的.. ..? – Blorgbeard 2011-03-08 00:23:57

回答

1

要做到這一點使用遞歸,使用模運算符(%),每次除以10,並向後積累您的結果字符串,直到您到達基本情況(0),在那裏沒有什麼可以分開。在基本情況下,您只需返回一個空字符串。

String doubleDigit(Integer digit) { 

     if (digit == 0) { 
     return ""; 
     } else { 
     Integer thisDigit = digit % 10; 
     Integer remainingDigits = (digit - thisDigit)/10; 
     return doubleDigit(remainingDigits) + thisDigit.toString() + thisDigit.toString(); 
     } 
    } 
+0

這是完美的。這正是我正在尋找的!非常感謝你!我從來沒有經常尋求編碼方面的幫助,但是這個讓我難住。非常感謝你! – Jeffrey 2011-03-08 01:19:12

0

您可以獲得給定整數的String.valueOf(doubleDigit)表示形式,然後使用Commons StringUtils(在我看來最簡單)來操作String。

如果你需要返回在這一點上的另一個數值(而不是新創建/操縱的字符串),你可以做Integer.valueOf(yourString)或類似的東西。

0

這裏沒有必要使用遞歸。

我不再是一個Java的傢伙,但算法我可能會使用的近似值是這樣的(在C#中的作品,應直接轉化爲Java):

int number = 3487; 
int output = 0; 
int shift = 1; 
while (number > 0) { 
    int digit = number % 10;     // get the least-significant digit  
    output += ((digit*10) + digit) * shift; // double it, shift it, add it to output 
    number /= 10;       // move to the next digit 
    shift *= 100;       // increase the amount we shift by two digits 
} 

這個解決方案應該工作,但現在我寫了它的麻煩,我意識到將數字轉換爲字符串並操作它可能更清楚。當然,這會慢一些,但你幾乎可以肯定不關心這樣一個小的速度差:)

編輯: 好了,所以你必須使用遞歸。你已經接受了一個完全正常的答案,但這裏是我的:)

private static long DoubleDigit(long input) {  
    if (input == 0) return 0;      // don't recurse forever! 
    long digit = input % 10;      // extract right-most digit 
    long doubled = (digit * 10) + digit;   // "double" it 
    long remaining = input/10;     // extract the other digits 
    return doubled + 100*DoubleDigit(remaining); // recurse to get the result 
} 

注意我切換到long所以多帶幾個數字作品。

+0

不幸的是我不得不使用遞歸,除此之外,你的代碼是完美的,它的確有訣竅。我只是負責在這個上使用遞歸:/ – Jeffrey 2011-03-08 01:18:26

1

如果你正在尋找它返回一個長而不是一個字符串,你可以使用下面的下面的解決方案的解決方案(非常類似於克里斯,爲0的假設爲基礎的情況下):

long doubleDigit(long amt) { 
    if (amt == 0) return 0;  
    return doubleDigit(amt/10) * 100 + (amt % 10) * 10 + amt % 10;   
} 

該函數當然受Java中的maximum size of a long的限制。

0

在構建Java程序時,我做了同樣的問題。這是我的解決方案,適用於負數和正數(並返回0爲0)。

public static int doubleDigits(int n) { 
    if (n == 0) { 
     return 0; 
    } else { 
     int lastDigit = n % 10; 
     return 100 * doubleDigits(n/10) + 10 * lastDigit + lastDigit; 
}