如何解决这个 Java 回文算法?
How to fix this Java palindrome algorithm?
MrSmith42 建议的解决方案:p for 循环出错。更正了它。
我尝试编写 ProjectEuler.net 档案中第四题的代码。需要找到最大的回文数,它是两个 3 位数的乘积。
我知道这段代码不是最有效的。首先,它高达 999,999。当最大值不应超过 999*999 = 998,001 时。我只想解决这个问题。但是我不知道我是否可以使用 Strings 或 String Tokenizer 来解决这个问题。
public class Main {
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>();
int a = 100000, b = 10000, c =1000, d = 100, e = 10, f = 1;
int m, n, p, q, s, t;
//The plan is to increment the numbers by one, starting from 100,000 upto 999,999.
for (m = 1; m <= 9; m++) {
for (n = 0; n <= 9; n++) {
for (p = 0; n <= 9; n++) {
for (q = 0; q <= 9; q++) {
for (s = 0; s <= 9; s++) {
for (t = 0; t <= 9; t++) {
if (t*a + s*b + q*c + p*d + n*e + m*f == m*a + n*b + p*c + q*d + s*e + t*f) {
arr.add(m*a + n*b + p*c + q*d + s*e + f*t); }}}}}
}
}
for (int x: arr)
System.out.println(x);
}
}
我正在获取格式为 ST00TS 的号码。所以,并不是所有的回文都被涵盖了。我不知道我哪里搞砸了。
循环头中存在复制和粘贴错误:
for (p = 0; p <= 9; p++) { // not (p = 0; n <= 9; n++)
MrSmith42 建议的解决方案:p for 循环出错。更正了它。
我尝试编写 ProjectEuler.net 档案中第四题的代码。需要找到最大的回文数,它是两个 3 位数的乘积。
我知道这段代码不是最有效的。首先,它高达 999,999。当最大值不应超过 999*999 = 998,001 时。我只想解决这个问题。但是我不知道我是否可以使用 Strings 或 String Tokenizer 来解决这个问题。
public class Main {
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>();
int a = 100000, b = 10000, c =1000, d = 100, e = 10, f = 1;
int m, n, p, q, s, t;
//The plan is to increment the numbers by one, starting from 100,000 upto 999,999.
for (m = 1; m <= 9; m++) {
for (n = 0; n <= 9; n++) {
for (p = 0; n <= 9; n++) {
for (q = 0; q <= 9; q++) {
for (s = 0; s <= 9; s++) {
for (t = 0; t <= 9; t++) {
if (t*a + s*b + q*c + p*d + n*e + m*f == m*a + n*b + p*c + q*d + s*e + t*f) {
arr.add(m*a + n*b + p*c + q*d + s*e + f*t); }}}}}
}
}
for (int x: arr)
System.out.println(x);
}
}
我正在获取格式为 ST00TS 的号码。所以,并不是所有的回文都被涵盖了。我不知道我哪里搞砸了。
循环头中存在复制和粘贴错误:
for (p = 0; p <= 9; p++) { // not (p = 0; n <= 9; n++)