Java recursive pen questions

Today, when the practice of Java pen questions, met a recurrent topic was about the beginning of time into it, and then I want to know is a parameter stack into question

public class test1 {

    public static void main(String[] args) {
        split(12);
    }

    public static int split(int number) {
        if (number > 1) {
            if (number % 2 != 0) System.out.print(split((number + 1) / 2));
            System.out.print(split(number / 2));
        }
        return number;
    }
}

The problem is the method of investigation into the stack with the order of the stack, advanced after
there is knowledge, at the time a stack method of execution is the return statement. Because it means the end of the stack and consumption methods, if there is no return statement, then the method the stack when nothing is executed directly destroyed.
1. When performing split (12), execution of the code of System.out.print (Split (Number / 2))
Split (12/2) into the stack, this time number = 6;
2. performing split (6), executing code of System.out.print (Split (Number / 2))
Split (6/2) into the stack, this time number = 3;
3. performing Split (. 3),
. 1
2
. 3
! row 1 if (number% 2 = 0)
the second row System.out.print (split ((number + 1 ) / 2));
line 3 System.out.print (split (number / 2) );
execution order
to execute the second row
first split ((3 + 1) / 2) into the stack, this time number = 2,
then execute Split (2), then split (2/2) into the stack, this time number = 1, and finally return 1,
note that at this time the second line does not end
at this time
split (2/2) at the stack output. 1;
Split ((+. 1. 3) / 2) at the stack output 2;
The second end of the line, and then execute the third row, this time number = 3, execution of System.out.print (Split (Number / 2))
Split (] 3/2) into the stack, number = 1, return, then need a stack of
split (3/2) at the stack output. 1
Split (6/2) at the stack output. 3
Split (12/2) out of the stack, the output 6;
final result 12136;

Split (number) method returns the final value of this number, so Split output (n) out of the stack is n

Finishing:
Split (12/2) into the stack
split (6/2) into the stack

split ((3 + 1) / 2) into the stack
split (2/2) into the stack
split (2/2) at the stack output. 1
split ((3 + 1) / 2) at the stack output 2

split (2/2) into the stack
split (2/2) at the stack output 1

split (6/2) at the stack output. 3
Split (12/2) out of the stack, the output 6

Published an original article · won praise 1 · views 46

Guess you like

Origin blog.csdn.net/qq_41600383/article/details/104074778