更新时间:2021-12-30 06:31:35
这似乎是一个很大的code。您是否尝试过一个非常幼稚的做法吗?检查东西是否是一个回文其实很简单。
This seems like a lot of code. Have you tried a very naive approach yet? Checking whether something is a palindrome is actually very simple.
private boolean isPalindrome(int possiblePalindrome) {
String stringRepresentation = String.valueOf(possiblePalindrome);
if ( stringRepresentation.equals(stringRepresentation.reverse()) ) {
return true;
}
}
现在可能不是最高效的code,但它给你一个非常简单的出发点:
Now that might not be the most performant code, but it gives you a really simple starting point:
private int nextLargestPalindrome(int fromNumber) {
for ( int i = fromNumber + 1; ; i++ ) {
if ( isPalindrome( i ) ) {
return i;
}
}
}
现在,如果觉得不够快,你可以把它作为一个参考实现,并在降低算法复杂度的工作。
Now if that isn't fast enough you can use it as a reference implementation and work on decreasing the algorithmic complexity.
有实际上应该是一个固定时间(以及其为线性上的输入的位数)的方式找到下一个最大的回文。我给一个算法,假定的数目是偶数的位长(但可扩展到的奇数个数字)。
There should actually be a constant-time (well it is linear on the number of digits of the input) way to find the next largest palindrome. I will give an algorithm that assumes the number is an even number of digits long (but can be extended to an odd number of digits).
应用到更复杂的数:
1. 1234567887654322
2. 12345678 87654322
3. 12345678 87654322
^ ^ equal
3. 12345678 87654322
^ ^ equal
3. 12345678 87654322
^ ^ equal
3. 12345678 87654322
^ ^ equal
3. 12345678 87654322
^ ^ equal
3. 12345678 87654322
^ ^ equal
3. 12345678 87654322
^ ^ equal
3. 12345678 87654322
^ ^ greater than, so increment the left
3. 12345679
4. 1234567997654321 answer
此似乎有点类似于你所描述的算法,但它开始于内的数字,并移动到外
This seems a bit similar to the algorithm you described, but it starts at the inner digits and moves to the outer.