找出多个整数中最大的回文
Find the biggest palindrome in multiple integers
我的某些算法有问题。我必须写一个 java 应用程序,
它找到预定数量的数字(n)的预定数量(l)的乘积的最大回文。例如,对于 l=2 和 n=2,最大的回文数是 9009 (91 * 99)。
我写了一个回文检查器,但我不知道如何将适当数量的数字乘以给定的位数。
有人可以帮我吗?
对不起我的英语。
这里是通过 l
数字与 n
数字的所有组合进行迭代的可能实现:
public static int[] iterate(int l, int n) {
int minNum = (int) Math.pow(10, n - 1);
int maxNum = (int) Math.pow(10, n) - 1;
// init array with `l` numbers with `maxNum` value
int[] numbers = new int[l];
Arrays.fill(numbers, maxNum);
// iterate through all combinations of numbers
while (true) {
System.out.println(Arrays.toString(numbers)); // for debug only
// calc multiplication of current combination of numbers
long mul = 1;
for (int num : numbers) {
mul *= num;
}
if (isPalindrome(mul)) {
return numbers; // biggest palindrome found
}
// calc next combination of numbers
boolean allMaxNums = true;
for (int j = l - 1; j >= 0; --j) {
--numbers[j];
if (numbers[j] < minNum) {
numbers[j] = maxNum; // need to reduce next number, go to the next j
} else {
// now all numbers in [minNum, maxNum] bounds
allMaxNums = false;
break;
}
}
if (allMaxNums) {
break; // returned to the initial combination
}
}
return null; // palindrome not found
}
private static boolean isPalindrome(long mul) {
// your check here
return false;
}
编辑
不幸的是,我以前的解决方案是不正确的,我们必须按其产品的降序迭代数字组合(而不是像我所做的那样按其他顺序)。我认为工作代码比我混乱的解释更好,所以你可以在这里看到我的新解决方案:https://ideone.com/ZSQC5d.
我的某些算法有问题。我必须写一个 java 应用程序, 它找到预定数量的数字(n)的预定数量(l)的乘积的最大回文。例如,对于 l=2 和 n=2,最大的回文数是 9009 (91 * 99)。
我写了一个回文检查器,但我不知道如何将适当数量的数字乘以给定的位数。
有人可以帮我吗?
对不起我的英语。
这里是通过 l
数字与 n
数字的所有组合进行迭代的可能实现:
public static int[] iterate(int l, int n) {
int minNum = (int) Math.pow(10, n - 1);
int maxNum = (int) Math.pow(10, n) - 1;
// init array with `l` numbers with `maxNum` value
int[] numbers = new int[l];
Arrays.fill(numbers, maxNum);
// iterate through all combinations of numbers
while (true) {
System.out.println(Arrays.toString(numbers)); // for debug only
// calc multiplication of current combination of numbers
long mul = 1;
for (int num : numbers) {
mul *= num;
}
if (isPalindrome(mul)) {
return numbers; // biggest palindrome found
}
// calc next combination of numbers
boolean allMaxNums = true;
for (int j = l - 1; j >= 0; --j) {
--numbers[j];
if (numbers[j] < minNum) {
numbers[j] = maxNum; // need to reduce next number, go to the next j
} else {
// now all numbers in [minNum, maxNum] bounds
allMaxNums = false;
break;
}
}
if (allMaxNums) {
break; // returned to the initial combination
}
}
return null; // palindrome not found
}
private static boolean isPalindrome(long mul) {
// your check here
return false;
}
编辑
不幸的是,我以前的解决方案是不正确的,我们必须按其产品的降序迭代数字组合(而不是像我所做的那样按其他顺序)。我认为工作代码比我混乱的解释更好,所以你可以在这里看到我的新解决方案:https://ideone.com/ZSQC5d.