java - 冰雹序列,递归,缺少 1 个案例

标签 java recursion sequence collatz

我有以下冰雹序列代码,适用于除 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/

相关文章:

python - 使用对象递归打印家谱

c++ - 递归函数是否比非递归函数慢

r - 如何识别R中的序列

sql-server - T-SQL 识别中断的日期序列中的差距

TCP序列号

java - 如何使用声明的数组

java - 如何将 iText 文档转换为 javax.activation.DataSource?

java - 应用程序想要访问过时版本的 Java : warning while invoking JNLP file

java - 递归方法为什么会停止?

java - 在带有 SonarQube 的 Java 中,如何修复 `Only the sign of the result should be examined`