简体   繁体   English

无法阅读简单的递归代码(JAVA)

[英]Having trouble reading a simple recursion code(JAVA)

Hello I am studying recursion and having trouble reading the following code below您好,我正在学习递归,但在阅读以下代码时遇到问题

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);
    }
}

I had two possible solutions(and realized both are wrong)我有两种可能的解决方案(并意识到两者都是错误的)

Solution 1解决方案1

  1. x = 13, y = 2, print(13 % 2) which is 1 x = 13, y = 2, print(13 % 2) 即 1
  2. x = 6 , y = 2, print( 6 % 2) which is 0 x = 6 , y = 2, print( 6 % 2) 即 0
  3. x = 3 , y = 2, print( 3 % 2) which is 1 x = 3 , y = 2, print( 3 % 2) 即 1
  4. x = 1 , y = 2, print( 1 % 2) which is 1 x = 1 , y = 2, print( 1 % 2) 即 1
  5. x = 0 , y = 2, since x == 0, return nothing and stop recursion. x = 0 ,y = 2,因为 x == 0,什么都不返回并停止递归。

therefore 1011因此 1011

Solution 2解决方案2

  1. x = 13, y = 2, mysteryMethod(13 / 2, 2) which is mysteryMethod(6, 2) since 6 != 0 go to next step x = 13, y = 2, mysteryMethod(13 / 2, 2) 是 secretMethod(6, 2) 因为 6 != 0 进入下一步
  2. x = 6 , y = 2, mysteryMethod(6 / 2, 2) which is mysteryMethod(3, 2) since 3 != 0 go to next step x = 6 , y = 2, mysteryMethod(6 / 2, 2) 是 secretMethod(3, 2) 因为 3 != 0 进入下一步
  3. x = 3 , y = 2, mysteryMethod(3 / 2, 2) which is mysteryMethod(1, 2) since 1 != 0 go to next step x = 3 , y = 2, mysteryMethod(3 / 2, 2) 是 secretMethod(1, 2) 因为 1 != 0 进入下一步
  4. x = 1 , y = 2, mysteryMethod(1 / 2, 2) which is mysteryMethod(0, 2) since 0 == 0 return nothing and stop recursion. x = 1 , y = 2, mysteryMethod(1 / 2, 2) 是 secretMethod(0, 2) 因为 0 == 0 不返回任何内容并停止递归。

therefore return nothing因此什么都不返回

but the correct answer was 1101但正确答案是 1101

Can anyone have a look at the code and explain me why 1101 is the correct answer and why my solutions are wrong?任何人都可以查看代码并解释为什么 1101 是正确答案以及为什么我的解决方案是错误的?

That is because you did the recursion then print the number, you should print the number then recursion, that is:那是因为你做了递归然后打印数字,你应该打印数字然后递归,即:

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);
        }
    }

In you code, you're printing the number backward...在您的代码中,您正在向后打印数字...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM