[英]Algorithm to find number of palindromes in interval
我目前的任务是编写一个程序,从<2;36>
的间隔计算任何基数的回文数。 问题是我的解决方案充其量只有O(n^2)
的时间复杂度,也就是说,如果我坦率地说,真的很慢。
到目前为止,我已经尝试过一些简单的解决方案,例如将所有数字从区间转换为所需的基数,将数字转换为数组,然后一一检查每个元素。
这是我到目前为止所得到的:
int isTrue = 1;
int arr[64];
while(n > 0)
{
arr[counter] = n % base;
n = n / base;
counter++;
}
for(int i = 0; i < counter; i ++)
{
if(arr[i] != arr[counter - i - 1])
{
isTrue = 0;
break;
}
}
无论如何它都不好,但它确实适用于基本测试。 问题是我目前正在尝试解决适用于更大数字的奖金之一。
通过更大的数字,我的意思是跨越数十亿数字的间隔,其中一个输入是例如:
c 15 62103360044 155888062462
Result : 123502
其中 c 是程序应该执行的任务(有 l 选项列出了在奖励测试中没有出现的所有回文),15 是基数,另外两个数字是间隔的限制。
我应该在一秒钟内计算五个这样的间隔的回文,老实说,我很困惑。
我会很感激任何帮助,如果我的问题格式错误或过于冗长,我很抱歉 - 这是我第一次在这里提出问题。
更快地进行回文检查是一个小的优化。 最初我什至会使用 java 的数字到字符串的转换。
你想要的是在更大的飞跃中跨过这个区间。
您可以在算法的初始版本中使用递归进行简化。
让我们寻找以 10 为底的:
62_103_360_044
155_888_062_462
6 ... 6 (recursion on the middle part)
7 ... 7
8 ... 8
9 ... 9
1 ... 1
你需要:
counter
)对于这一步,您只需要增加一个数字,甚至可以作为 char 完成。
另请注意,对...的递归调用对 7、8 和 9 给出相同的结果,开始 000..000 和结束 999..999。
这将大大加快。 快乐编码。
递归的使用:我没有给出一个明确的答案,因为这会打败任务的挑战。
public BigInteger palindromesInInterval(int base, BigInteger from, BigInteger to) {
return palindromesRec(base, from.toString(base), to.toString(base));
}
private BigInteger palindromesRec(int base, String from, String to) {
// Do the simple work:
if (from.length() > to.length()) {
return BigInteger.ZERO;
}
if (from.length() == to.length() && from.compareTo(to) > 0) {
return BigInteger.ZERO;
}
if (from.length() == 1) {
...
}
// Do a step:
int highDigit = Integer.parseInt(from.substring(0, 1), base);
int lowDigit = Integer.parseInt(from.substring(from.length() - 1), base);
BigInteger sum = BigInteger.ZERO;
int digit = Math.max(highDigit, lowDigit);
String from2 = from.substring(1, from.length() - 2); // Can start with 0
String to2 = "1000...000" -1; // Niners so to say.
while (digit < base) {
...
sum = sum.add(palidromesRec(base, from2, to2)); // RECURSION
from2 = "000...000";
}
...
return sum;
}
递归调用自己,这里只调用一次,没有额外的参数,经常用到。 例如,将工作拆分为:
from 6 2_103_360_04 4
to 9 9 .. 9 9
from 1 00 .. 0 1
to 1 55_888_062_46 2
并计算每个 X
from X 000 X (n zeroes)
to X 999 X (n time (base-1))
作为基础(n+1)/2 。
为此,您需要一定程度的抽象/简化。 把事情简单化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.