简体   繁体   English

为什么递归数值方法会输出其输出

[英]why does recursive numeric method print out its output

Can anyone tell me in the simplest way why this prints out 321123 when generate(123) is called? 谁能以最简单的方式告诉我为什么调用 generate(123)时会打印出321123吗? I understand why it prints out 321, but the 123 part eludes me. 我了解为什么它会打印出321,但是我却看不到123部分。

 /** @param x an integer such that x >= 0
 */ 

public void generate(int x) {     

     System.out.print(x % 10);     

     if ((x / 10) != 0) {         
        generate(x / 10);     
     }     
     System.out.print(x % 10); 
}

The recursion goes "in", then comes back "out". 递归“输入”,然后返回“输出”。 Think of it this way: 这样想:

generate(123) {
    System.out.print(123 % 10)          // 3

    generate(12) {
        System.out.print(12 % 10)       // 2

        generate(1) {
            System.out.print(1 % 10)    // 1
            System.out.print(1 % 10)    // 1
        }

        System.out.print(12 % 10)       // 2
    }

    System.out.print(123 % 10)          // 3
}

Because you print x%10 both before and after your recursive call. 因为您在递归调用之前和之后都打印x%10 When the number is 123, it prints 3, does the work for 12, then prints 3 again. 当数字是123时,它将打印3,对12进行打印,然后再次打印3。

When it gets 12, it prints 2, does the work for 1, then prints 2 again. 当它变为12时,将打印2,对1做功,然后再次打印2。

Same for the 1. So you get "nested" prints of the remainder in each call. 与1相同。因此,您将在每个呼叫中​​“嵌套”打印其余部分。

Entrance to deeper function levels: 进入更深层次的功能:

if ((x / 10) != 0) { 如果((x / 10)!= 0){
generate(x / 10); 生成(x / 10);
} }

is also exit with the filo order which reverses 321 to 123 也以反序退出321至123

becasue there is another 因为还有另一个

System.out.print(x % 10); System.out.print(x%10);

after that. 之后。

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

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