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 ?
views:
495answers:
3
+3
A:
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.
Petr Topol
2009-10-04 09:53:38
That’s the same I came up with, so +1.
Konrad Rudolph
2009-10-04 09:58:28
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
2009-10-04 10:02:16
Another edge case to consider is if the input is the last 15-digit palindrome ("999999999999999").
Martin B
2009-10-04 10:06:29
@Martin B - you are absolutely right.
Petr Topol
2009-10-04 10:19:02
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
2009-10-04 10:25:57
Oh, I forgot: in the last case, flip the incremented first part and use that as the new last part.
bart
2009-10-04 10:30:53
+1
A:
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.
waxwing
2009-10-04 09:54:03
+10
A:
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
Pete Kirkham
2009-10-04 10:11:18