I recently came across a problem to find the Next Palindrome Number. For example, the next palindrome after 2133 is 2222.
Palindrome: is a word, phrase, number or other sequence of units that can be read the same way in either direction (the adjustment of punctuation and spaces between words is generally permitted(.
The common way to solve this problems is brute-force approach where we keep increment the integer until we hit palindrome.
Palindrome: is a word, phrase, number or other sequence of units that can be read the same way in either direction (the adjustment of punctuation and spaces between words is generally permitted(.
The common way to solve this problems is brute-force approach where we keep increment the integer until we hit palindrome.
public static String bruteForce(String s){
BigInteger i = new BigInteger(s) ;
while(true){
i = i.add(BigInteger.ONE);
final String result = i.toString();
if(isPalindrome(result)){
return result;
}
}
}This approach is VERY slow for large numbers! A faster way is "mirroring" the number about its centre. For example, the mirror of 65432 is 65456, which is the next palindrome. The following method mirrors a string:public static String mirror(String s) {
final char[] arr = s.toCharArray();
int midpoint = arr.length / 2;
int i=arr.length%2==0?midpoint:midpoint+1;
while (i < arr.length) {
arr[i] = arr[midpoint - 1];
i++;
midpoint--;
}
return new String(arr);
}
BUT sometimes a mirrored number might be smaller than the original. For example, the mirror of 12345 is 12321, which is smaller. In this case, we need to increment the original number from the middle and then mirror it. So when 12345 is incremented from the middle, you get 12445 which mirrors to 12421, the next palindrome. Incrementing from the middle can get tricky if there is a 9 in the middle. For example, 12945 increments to 13045 which then mirrors to 13031. The following method increments a number from the middle:
public static String incrementFromMiddle(String s) {
final char[] arr = s.toCharArray();
final int midpoint = arr.length / 2;
int currPoint=arr.length%2==0?midpoint-1:midpoint;
boolean found = false;
while (currPoint >= 0 && !found) {
char c = arr[currPoint];
char inc;
if (c == '9') {
inc = '0';
}
else {
inc = (char) (c + 1);
found = true;
}
arr[currPoint] = inc;
if (!found) {
currPoint--;
}
}
if (!found) {
// we have fallen off the start of the string
// example 999 has become 009. Add a one on to give: 1009
final char[] newarr = new char[arr.length + 1];
newarr[0] = '1';
System.arraycopy(arr, 0, newarr, 1, arr.length);
return new String(newarr);
}
else {
return new String(arr);
}
}
No comments:
Post a Comment