一尘不染

从for循环中找到最大值

java

我创建的代码为我寻找回文数时提供了数千种解决方案。任务是找到可能的最高编号:

 public static void main(String[] args) {
        long product;
        outer: for (int i = 999; i >= 100; i--) {
            for (int j = 999; j >= 100; j--) {
                product = j * i;
                if (reverse(product)) {
                    System.out.printf("%d * %d = %d%n", i, j, product);
                    continue;
                }
            }
        }
    }
    private static final boolean reverse(long value) {
        String str = String.valueOf(value);
        return str.equals(new StringBuilder(str).reverse().toString());
    }}

如何使代码仅显示for循环创建的最大值?


阅读 1470

收藏
2020-12-03

共1个答案

一尘不染

该答案在代码中描述为解决方案:

long highest_palindrome = 0L;
int storeI = 0;
int storeJ = 0;
long product;
outer: for (int i = 999; i >= 100; i--) {
    for (int j = 999; j >= 100; j--) {
        product = j * i;
        if (product < highest_palindrome) break;
        if (reverse(product)) {
            if (product > highest_palindrome) {
                highest_palindrome = product;
                storeI = i;
                storeJ = j;
            }
            continue;
        }
    }
}

System.out.printf("%d * %d = %d%n", storeI, storeJ, highest_palindrome);
2020-12-03