gpt4 book ai didi

java - 递归神秘法——有人可以给我解释一下吗?

转载 作者:行者123 更新时间:2023-11-30 03:10:12 27 4
gpt4 key购买 nike

对于以下方法,当调用 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 + " ");
}
}

最佳答案

它是递归的,所以调用看起来像这样。

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 + " ");

关于java - 递归神秘法——有人可以给我解释一下吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33763297/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com