Please explain ths recursion step by step [closed]

2020-05-10 09:15发布

问题:

Please explain ths recursion step by step;

public class TestClass {

    private static void printit(int i) {
        if (i == 1) {
            return;
        }
        System.out.println(i);
        printit(i / 2);
        printit(i / 2);
    }

    public static void main(String args[]) {
        int i = 8;
        printit(i);
    }
}

回答1:

If you're using IDE you can just use the debugger and see with you own eyes what's happening step by step.

Anyway, let's try and what happens when we call the recursive method: You call the method with 8 (printit(8);):

  1. System.out.println(8); -> 8
  2. printit(8 /2 ); -> Call to method again with 8/2=4
  3. System.out.println(4); -> 4
  4. printit(4 /2 ); > Call to method again with 4/2=2
  5. System.out.println(2); -> 2
  6. printit(2 /2 ); > Call to method again with 2/2=1
  7. return; -> Continues with previous call, the (printit(4 /2);)
  8. printit(2 /2 ); > Call to method again with 2/2=1
  9. return; -> Continues with previous call, the (printit(4 /2);)
  10. method finishes, continues with the previous call (printit(8 /2);)
  11. printit(4 /2 ); > Call to method again with 4/2=2
  12. System.out.println(2); -> 2
  13. calls printit(2/2); which we already know result in nothing.
  14. Now we are in the first call again, the printit(8);, calling for printit(8/2);
  15. System.out.println(4); -> 4
  16. 16 etc...