[英]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.