1

For the following method, when mystery(45) is called, the output is "1 0 1 1 0 : 2 5 11 22 45". I understand why "1 0 1 1 0 :" is printed out, but don't understand how "2 5 11 22 45" is printed out after the colon. Can someone explain this to me? I've tried writing it out, but I just could not figure it out.

public static void mystery (int n) {
   if (n <= 1) {
       System.out.print(": ");}
   else {
      System.out.print((n % 2) + " ");
      mystery (n/2);
      System.out.print(n + " ");
   }
}
bd7349
  • 19
  • 3
  • 1
    Have you tried debugging through it? That's the most obvious way that you'll see what's happening. Keep an eye on the call stack at all times... and add more logging if that helps. – Jon Skeet Nov 17 '15 at 17:30
  • Try executing the code and writing the results on a piece of paper by yourself and then you will resolve the mystery. – Luiggi Mendoza Nov 17 '15 at 17:30

1 Answers1

2

It's recursive, so the calling looks something like this.

System.out.print((45 % 2) + " ");
    System.out.print((22 % 2) + " ");
        System.out.print((11 % 2) + " ");
            System.out.print((5 % 2) + " ");
                System.out.print((2 % 2) + " ");
                    mystery (2 / 2); <-- won't recurse anymore, will just print :
                System.out.print(2 + " ");
            System.out.print(5 + " ");
        System.out.print(11 + " ");
    System.out.print(22 + " ");
System.out.print(45 + " ");
Zereges
  • 5,139
  • 1
  • 25
  • 49