对于以下方法,当调用mystery(45)时,输出为“1 0 1 1 0:2 5 11 22 45”。我理解为什么打印出“1 0 1 1 0:”,但不明白结肠后打印出“2 5 11 22 45”的原因。谁可以给我解释一下这个?我已经尝试过写出来了,但我无法理解它。
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 + " ");
}
}
答案 0 :(得分:2)
这是递归的,所以调用看起来像这样。
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 + " ");