解决Project Euler#4的问题



问题读取

回文数字的两种读法都是一样的。最大的回文由两个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);
            }
        }
      }
    }
   }

以下是适用于您的代码。

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

最新更新