Skip to content

Instantly share code, notes, and snippets.

@juanfal
Created December 7, 2012 10:40
Show Gist options
  • Save juanfal/4232412 to your computer and use it in GitHub Desktop.
Save juanfal/4232412 to your computer and use it in GitHub Desktop.
Largest palindrome using string
// 004.palindromeLargest.cpp
// juanfc 2012-06-24
// A palindromic number reads the same both ways. The largest palindrome made
// from the product of two 2-digit numbers is 9009 = 91 x 99.
// Find the largest palindrome made from the product of two 3-digit numbers.
#include <iostream>
#include <sstream>
using namespace std;
const int NOOFDIGITS = 3;
int largestPalWith(int N);
bool numIsPalind(int);
bool isPal(string s);
int main()
{
cout << "The largest palindrome resulting of the mult. of numbers of "
<< NOOFDIGITS << " x " << NOOFDIGITS << " is: ";
int greatestPal = largestPalWith(NOOFDIGITS);
if ( greatestPal == 0 )
cout << "None" << endl;
else
cout << greatestPal << endl;
return 0;
}
int largestPalWith(int N)
{
// find the limits
int baseTop = 1;
for (int i = 0; i < NOOFDIGITS; ++i) {
baseTop *= 10;
}
int baseBot = baseTop / 10;
int greatestPal = 0;
int ii, jj;
int test;
for (int i = baseTop-1; i >= baseBot; i--) {
for (int j = baseTop-1; j >= i; j--) {
test = i * j;
if (numIsPalind(test) and test > greatestPal) {
greatestPal = test;
ii = i;
jj = j;
}
}
}
return greatestPal;
}
bool numIsPalind(int a)
{
// here you need to convert the int to its decimal string chars
// it can be done several ways:
stringstream ss;
ss << a;
string s = ss.str();
return isPal(s);
}
bool isPal(string s)
{
int i = 0;
int j = s.length()-1;
while (i < j and s[i] == s[j]) {
++i;
--j;
}
return i >= j;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment