Recursion

AP Computer Science A· difficulty 3/5

public static void hanoi(int n, char from, char to, char via) {
  if (n == 0) return;
  hanoi(n - 1, from, via, to);
  System.out.println(from + "->" + to);
  hanoi(n - 1, via, to, from);
}

How many print statements occur for n=4?

  • A

    7

  • B

    8

  • C

    15

    check_circle
  • D

    16

Explanation

The number of prints equals 2^n - 1 = 15 for 4 disks.

Want 10 more like this — adaptive to your weak spots?

Related questions