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
Code Kata: Project Euler #4, Finding Palindromes
Posted by md
on April 19, 2008
This weekend, I solved problem 4 of Project Euler:
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]-.