Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if given a 15 digit number whats the best way to find the next palindrome?

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 ?

like image 298
Vaibhav Avatar asked Oct 04 '09 09:10

Vaibhav


2 Answers

  • Split the number into three parts, head, mid, tail

    1345673 2 9807541

  • 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 head part and set mid := 0
  • result := head mid reverse(head).

    1345673 3 reverse(1345673) => 134567333765431

like image 181
Pete Kirkham Avatar answered Sep 23 '22 00:09

Pete Kirkham


I believe it's like this

  1. Split the number into three parts 1345673 2 9807541
  2. Flip the last one 1457089
  3. If it's larger than the first part (it is in this case)
    • firstpart++
    • middlepart = 0
  4. flip first part and replace last part.
like image 30
Petr Topol Avatar answered Sep 20 '22 00:09

Petr Topol