为什么我的3n + 1解决方案不起作用?

时间:2014-09-08 20:16:10

标签: java eclipse

我的类赋值是编写一个方法,返回一个字符串,该字符串由一个以正整数n开头并以1结尾的Hailstone序列组成。字符串应由一系列数字组成,每个数字后跟一个空格。当序列中出现数字m(除1之外)时,应该跟nextHailstone(m)。例如,nextHailstone(1)应返回" 1"和nextHailstone(5)应该返回" 5 16 8 4 2 1"。

我有以下代码,无法弄清楚它为何陷入无限循环。

public static int nextHailstone (int n)
{
    if (n==1)
    {
        return n;
    }
    if (n%2 == 0)
    {
        return n/2;
    }
    else
    {
        return ((3*n)+1);
    }
}

public static String hailstones (int n)
{
    String result = "";
    result+=n;
    result+= ' ';

    while (true)
    {
        if (result.charAt(result.length()-2)=='1')
        {
            return result;
        }
        else
        {
            result +=(nextHailstone(result.charAt(result.length()-2)) + ' ');
        }
    }
}

测试用例:

public void testHailstones ()
{
    assertEquals("1 ", hailstones(1));
    assertEquals("16 8 4 2 1 ", hailstones(16));
    assertEquals("7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 ", hailstones(7));
}

2 个答案:

答案 0 :(得分:1)

你陷入无限的原因是你有一个while(true)循环。除非破坏,否则这将无限运行。你永远不会让if语句成立,所以它会不断运行。

答案 1 :(得分:1)

您正在将result.charAt(result.length()-2)传递给nextHailstone。这意味着您传递charnextHailstone对其int值进行操作,而不是char所代表的数字。此外,您只需将char传递给nextHailstone。您不处理多位数字。

例如,假设您尝试halstones (1)

您将result设置为“1”。然后你将'1'传递给nextHailstone。但是字符'1'是49 int。因此,不会像预期的那样返回1,而是返回49*3+1=148result将更新为“1 148”。

在下一步中,您将char {8'(忽略14)传递给nextHailstone56为int。你可以看到你的循环永远不会终止的原因。

您应该将序列存储在List int中,并且只有在准备好返回输出时才将其转换为String

您可以这样做:

public static String hailstones (int n)
{
    List<Integer> seq = new ArrayList<Integer>();
    seq.add(n);

    while (true)
    {
        if (seq.get(seq.size()-1)==1)
        {
            return seq.toString(); // You might have to change that if you require
                                   // the output in a different format
        }
        else
        {
            seq.add(nextHailstone(seq.get(seq.size()-1)));
        }
    }
}
相关问题