我在LeetCode上遇到一個問題,需要對遞歸進行更新。這是問題:遞歸添加數字
Given a non-negative integer num, repeatedly add all its digits until
the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit,
return it.
我已經看到使用while循環的答案,但我想試試這與遞歸。 這是我到目前爲止有:
public int AddDigits(int num) {
if(num > 9)
{
num = (num%10) + (num/10);
AddDigits(num);
}
else{
return num;
}
}
首先,我得到"Not all code paths return a value."
但是基於if
布爾檢查,應該不會這是好嗎?即使我else塊後添加return num
,我仍然得到11.使用29的輸入,我的解決方案返回11,即使num
最終成爲2.我上面的遞歸解決方案,該return num
部分多次出現(我與測試Console.WriteLine語句) - 這是由於堆棧?
這是我想知道的內容 - 遞歸調用後爲什麼會發生的代碼 - 或者應該遞歸調用通常遞歸調用後,不包括代碼?
另外,我怎麼能得到這個遞歸和不使用while循環工作?
'回報AddDigits(NUM);' – spender
「爲什麼代碼遞歸調用後發生 - 或者應該通常遞歸調用遞歸調用後,不包括代碼?」查閱術語「尾遞歸」以在此找到答案。 – spender