【问题标题】:Why isn't the if statement working?为什么 if 语句不起作用?
【发布时间】:2014-01-17 00:30:34
【问题描述】:

我试图用 Java 解决 Project Euler 的问题。问题4。

http://projecteuler.net/problem=4

它说我必须找到由两个 3 位数的乘积构成的最大回文数。

所以这里是代码(只是不工作的部分):

public class Problem4PE {
    public static void main(String[] args){
        int result = 0;
        Integer output = 0;

        for (int i = 100; i < 1000; i++) {
            for (int j = 100; j < 1000; j++) {
                output = i*j;
                String strout = output.toString();
                StringBuilder stb = new StringBuilder();

                char[] chrout = strout.toCharArray();
                for (int x = 0; x < chrout.length; x++) {
                    stb.append(chrout[x]);
                }
                StringBuilder stres = new StringBuilder("");
                for (int k = chrout.length-1; k > -1 ; k--) {
                    stres.append(chrout[k]);
                }
                String stbb = stb.toString();
                String string = stres.toString();
                Boolean bool = stbb.equals(string);
                if (bool){
                    result = output;
                }

            }
        }
        System.out.println(result);
    }
}

所以上面的输出出来了:580085 但是当我提交它时,它显示不正确。我不理解为什么。那么您能否告诉我问题出在代码中,还是我在理解问题时有错误。

【问题讨论】:

  • 你可以做更多的事情来减少测试用例并找出失败的地方。
  • 这里有一个重要提示:添加一行打印output 任何时候bool 为真。 (将程序的输出重定向到一个文件,因为它可能非常大。)我敢打赌,如果你这样做并查看结果,你会弄清楚它为什么不起作用。

标签: java boolean conditional-statements palindrome


【解决方案1】:

您的代码跳过了最大的产品。

result 不能保证在for 循环的两次迭代之间增加,因此result 的最终值不是最大的。

【讨论】:

    【解决方案2】:

    试试这个

    if (bool && output > result) { // a second if condition.
      result = output;
    }
    

    它给了我正确的答案。

    【讨论】:

    猜你喜欢
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-23
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多