If given a 15 digit number what is the best way to find the next palindrome? for example what will be the next palindrome of: 134567329807541?
Algorithm:
Step1: Split the number into three parts,
1345673 2 9807541
Step2: Reverse
if(reverseHead == tail) {
if (m <= 9) {
m++;
} else {
m = 0;
h = h + 1;
}
}
Step3: Result is
result = head+ mid + rev(head)
= 1345673+ 3 + reverseHead
= 134567333765431
Algorithm:
Step1: Split the number into three parts,
head, mid, tailnumber = 134567329807541count = no. of characters = 15head = number.substring(0, count / 2) = number.substring(0,7) = 1345673mid = number.substring((count / 2), (count / 2) + 1) = number.substring(7,8) = 2tail = number.substring((count / 2) + 1) = number.substring(8) = 9807541
head mid tail 1345673 2 9807541
Step2: Reverse
head and compare it to tail 3765431- If
reverse(head) <= tail( if they are equal the initial input is a palindrome, and you want the next )- If
mid < 9, increment mid - Else increment
headpart and setmid := 0
- If
if(reverseHead == tail) {
if (m <= 9) {
m++;
} else {
m = 0;
h = h + 1;
}
}
Step3: Result is
head mid reverse(head). result = head
= 134567333765431
0 comments:
Post a Comment