问题解决项目欧拉#4

时间:2015-11-23 01:25:20

标签: java

问题在于

  

回文数字两种方式相同。最大的回文   由两个2位数字的乘积制成的9009 = 91×99。

     

找到由两个3位数的产品制成的最大的回文   号。

我不明白。在尝试扭转数字之前,我仔细检查了一切,但之后我在控制台中没有得到任何东西,但是0。

public class E4 {

public static void main(String[] args) {

    int product, rev = 0;

    for (int x = 0, y = 1; x <= 99 && y <= 99;) {
        product = x * y;                            //This for loop multiplies numbers from 0-99 * 1            
        if (x == 99) {                              //Then numbers from 0-99 * 2, and so on, until 99*99
            y++;
            x = 0;
        }
        x++;        

        while (product != 0) {
            rev = rev * 10;                        //This loop should reverse the products and then
            rev = rev + product % 10;              //The if loop should check if it is a palindrome number
            product = product / 10;                //But it doesn't work?

            if (rev == product) {
                System.out.println(rev);
            }

        }

      }
    }
   }

1 个答案:

答案 0 :(得分:0)

以下是适合您的代码。

public class E4 {

    public static void main(String[] args) {

        int product = 0;

        for (int x = 0; x < 100; x++) {
            for (int y = 0; y < 100; y++) {
                product = x * y;
                int rev = reverseInt(product);
                if (rev == product) {
                    System.out.println(rev);
                }

            }
        }
    }

    private static int reverseInt(int product) {
        int rev = 0;
        while (product != 0) {
            rev = rev * 10;
            rev += product % 10;
            product = product / 10;
        }
        return rev;
    }
}

你的部分问题是你的代码总是以product结尾为0(因为你的while循环改变了它,只在product == 0时退出)。此外,您永远不会将rev重置为0

相关问题