if given a 15 digit number whats the best way to find the next palindrome?
-
19-09-2019 - |
Question
in c++ what will be the fastest logic to find next palindrome of a given 15 digit number? for example what will be the next palindrome of: 134567329807541 ?
Solution
Split the number into three parts,
head
,mid
,tail
1345673 2 9807541
Reverse
head
and compare it totail
3765431If
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
head
part and setmid := 0
- If
result :=
head mid reverse(head)
.1345673 3 reverse(1345673) => 134567333765431
OTHER TIPS
I believe it's like this
- Split the number into three parts 1345673 2 9807541
- Flip the last one 1457089
- If it's larger than the first part (it is in this case)
- firstpart++
- middlepart = 0
- flip first part and replace last part.
I am not about to implement anything, but I imagine the logic would be:
- Split the number at the middle of the string: X being the left part and Y being the right part.
- Let X' = { X + 1 if reverse(X) < Y; X otherwise }
- The result is then concat(X',reverse(X'));
If the length is uneven, you need to treat the middle digit separately. But that is quite trivial.
I think the following algo should also work .. It is easier to implement also
i) Divide the given nos into three parts HEAD MID TAIL
ii) Add 1 to number HEAD MID
(in case of carry, follow basic addition rules)
iii) reverse the new HEAD(store it in HEAD_REV)
iv) required ans is:- 'new HEAD' MID HEAD_REV
Hoping that following example will help in better understanding of the algo
let nos be:- 23469 9 12367
So HEAD -> 23469 MID -> 9 TAIL --> 12367
step 2:- 23469 9 +1 = 23470 0
(now HEAD -> 23470 MID -> 0 HEAD_REV -> 07432 )
required Ans:-
23470 0 07432
Plz do infrom me if there exist any flaw in this procedure
Split the number into three parts head, mid and tail
if reverse(head)>tail
result := head mid reverse(head)
else if reverse(head)= tail && mid<9
mid++
result := head mid tail
else
mid =0
head++
result := head mid reverse(head)