gonium.net » palindrome http://gonium.net/md so much time, so little to do. Sat, 11 Sep 2010 16:42:09 +0000 en hourly 1 http://wordpress.org/?v=3.0.1 Code Kata: Project Euler #4, Finding Palindromes http://gonium.net/md/2008/04/19/code-kata-project-euler-4-finding-palindromes/ http://gonium.net/md/2008/04/19/code-kata-project-euler-4-finding-palindromes/#comments Sat, 19 Apr 2008 17:57:51 +0000 md http://gonium.net/md/?p=83 This weekend, I solved problem 4 of Project Euler:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.
I designed a routine that checks whether a given number is a palindrome. This routine is then used inside two loops iterating from 999 downto 0. The first hit is the largest palindrome. The core functionality is here: bool Problem4::isPalindrome(long number) { bool retval = false; std::vector digits; while (number > 0) { long lastdigit = number % 10; digits.push_back(lastdigit); number = number / 10; } reverse(digits.begin(), digits.end()); std::vector::iterator front = digits.begin(); std::vector::iterator back = –digits.end(); retval = false; while (! (front >= back)) { if ((*front) == (*back)) { retval = true; // move iterators to the next digits front++; back–; } else { // cannot be a palindrome, back out retval = false; break; } } return retval; } This implementation reverses the vector. By using the front and back operators in the other direction, this could be left out. But it serves its purpose for now. You can get the full sourcecode from the download page. Please note that the code in the tarball calculates *all* palindromes smaller than 1000000. The picture was CCed on flickr by TisseurDeToile -[mangerait bien un petit chat]-.]]>
http://gonium.net/md/2008/04/19/code-kata-project-euler-4-finding-palindromes/feed/ 0