我有以下冰雹序列代码,适用于除 1 序列之外的所有数字:
public class Recursion {
public static void main(String[] args) {
hailstone(16); // prints 16 8 4 2 1
hailstone(1); //prints just 1 instead of 1 4 2 1
}
public static void hailstone(int seed) {
String str = "" + seed;
if (seed == 1) {
System.out.print(str);
} else {
if (seed % 2 == 0) {
System.out.print(str + " ");
hailstone(seed / 2);
} else {
System.out.print(str + " ");
hailstone((3 * seed) + 1);
}
}
}
}
如何在保留递归方法和无效的情况下绕过这种特殊情况?
我不允许使用任何类型的循环。
最佳答案
1
是递归的退出点,这就是为什么你不能让它也像入口点一样。
如果更改退出点怎么办?将 2
设置为预退出点:
public static void hailstone(int seed) {
String str = "" + seed;
if (seed == 2) {
System.out.print(str + " 1");
} else {
if (seed % 2 == 0) {
System.out.print(str + " ");
hailstone(seed / 2);
} else {
System.out.print(str + " ");
hailstone((3 * seed) + 1);
}
}
}
public static void main(String[] args) {
hailstone(16);
System.out.println();
hailstone(15);
System.out.println();
hailstone(1);
System.out.println();
}
将打印:
16 8 4 2 1
15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
1 4 2 1
关于java - 冰雹序列,递归,缺少 1 个案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53673610/