[英]Having trouble reading a simple recursion code(JAVA)
您好,我正在學習遞歸,但在閱讀以下代碼時遇到問題
public class MysteryClass {
/**
* Mystery method that performs a function recursively.
*
* @param x an integer > 0
* @param y an integer > 0 and < x
* prints result
*/
public static void mysteryMethod(int x, int y) {
if (x == 0) {
return;
} else {
mysteryMethod(x / y, y);
System.out.print(x % y);
}
}
public static void main(String[] args) {
mysteryMethod(13,2);
}
}
我有兩種可能的解決方案(並意識到兩者都是錯誤的)
解決方案1
因此 1011
解決方案2
因此什么都不返回
但正確答案是 1101
任何人都可以查看代碼並解釋為什么 1101 是正確答案以及為什么我的解決方案是錯誤的?
那是因為你做了遞歸然后打印數字,你應該打印數字然后遞歸,即:
public static void mysteryMethod(int x, int y) {
if (x == 0) {
return;
} else {
System.out.print(x % y);//exchange the position of the two lines of code
mysteryMethod(x / y, y);
}
}
在您的代碼中,您正在向后打印數字...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.