Monday, April 19, 2010

I recently came across a challenging problem on SPOJ called The Next Palindrome. It involves finding the next palindrome given a very large integer (with more than 1000000 digits). For example, the next palindrome after 2133 is 2222.

A palindrome is any string which reads the same when read from left-to-right and right-to-left, for example, 818. Here is a method which tests if a string is a palindrome:

This approach is VERY slow for large numbers! A faster way is "mirroring" the number about its centre. For example, the mirror of
65432 is 65456, which is the next palindrome. The following method mirrors a string:

BUT sometimes a mirrored number might be smaller than the original. For example, the mirror of 12345 is 12321, which is smaller. In this case, we need to increment the original number from the middle and then mirror it. So when 12345 is incremented from the middle, you get 12445 which mirrors to 12421, the next palindrome. Incrementing from the middle can get tricky if there is a 9 in the middle. For example, 12945 increments to 13045 which then mirrors to 13031. The following method increments a number from the middle:

Subscribe to fahd.blog

Hi, I'm Fahd, a software developer at an investment bank in London. I am passionate about technology and work mainly with open source software, specialising in Java applications and Unix-based operating systems.

This blog is a place for me to share useful code snippets to solve problems that I have come across, and to write about ideas and experiences as a programmer.

All code on this blog has been written by me, unless stated otherwise, and you are free to use, share and adapt it for any purpose, under the terms of the GNU General Public License.

I love hearing back from my readers, so please feel free to leave comments! Thanks for reading and happy programming :-)