views:

495

answers:

3

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 ?

+3  A: 

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.
Petr Topol
That’s the same I came up with, so +1.
Konrad Rudolph
There's a little bug here, I think... For example, take a look at what happens to the input "13 5 09" (using a five-digit number for convenience). The next palindrome is "13 5 31", but the algorithm gives "14 0 41". To fix this, step 2 should be: Flip the *first* part, and step 3 should be: If it's smaller than the *last* part.
Martin B
Another edge case to consider is if the input is the last 15-digit palindrome ("999999999999999").
Martin B
@Martin B - you are absolutely right.
Petr Topol
There are so many bugs that I doubt your algorithm is even useful. 1. Flip the *first* part, and use as last part. If the result is larger than the original number, you're don. 2. If it's smaller, increment the *middle* part. 3. If the middle part was 9 (now 10), make it 0 and increment first part.
bart
Oh, I forgot: in the last case, flip the incremented first part and use that as the new last part.
bart
+1  A: 

I am not about to implement anything, but I imagine the logic would be:

  1. Split the number at the middle of the string: X being the left part and Y being the right part.
  2. Let X' = { X + 1 if reverse(X) < Y; X otherwise }
  3. 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.

waxwing
+10  A: 
  • 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

Pete Kirkham
and what if reverse(head)>tail ??
vaibhav
That's left as an exercise :-)
starblue
if reverse(head)>tail you continue with "result:=..."
hjhill