Oct 24, 2011 at 5:56pm UTC
This is code to find a palindrome within 10 tries by reversing the initial input and adding it to itself then checking if the sum is a palindrome.Give any opinions on how the code may be optimized.
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
bool ispalin(int q)
{
int lrgNum = 1000000000;
int reverseQ = 0;
int numle = 10;
int strgcnt = 0;
int arycntr = 0;
int originalQ;
originalQ = q;
while(q < lrgNum)
{
lrgNum = lrgNum/10;
numle = numle - 1;
}
int numstrg[numle];
while(numle > 0)
{
numstrg[strgcnt] = q%10;
strgcnt = strgcnt + 1;
numle = numle - 1;
q = (q-(q%10))/10;
}
int arbcnt = strgcnt;
while(arbcnt > 0)
{
reverseQ = (reverseQ*10)+numstrg[arycntr];
arbcnt = arbcnt - 1;;
arycntr = arycntr + 1;
}
cin.get();
bool tf = false;
if(originalQ == reverseQ)
{
tf = false;
}
else
{
tf = true;
}
return tf;
}
int main()
{
int x;
cout<<"Enter an integer."<<"\n";
cin>>x;
cin.get();
int counter = 0;
int reverseX = 0;
int numlength = 10;
int abtNum = 1000000000;
int storagecount = 0;
int sum;
int araycounter = 0;
int originalX;
bool notpalin = true;
originalX = x;
while(counter < 10 && notpalin == true)
{
counter = counter + 1;
while(x < abtNum)
{
abtNum = abtNum/10;
numlength = numlength - 1;
}
int numstorage[numlength];
while(numlength > 0)
{
numstorage[storagecount] = x%10;
storagecount = storagecount + 1;
numlength = numlength - 1;
x = (x-(x%10))/10;
}
int arbcount = storagecount;
while(arbcount > 0)
{
reverseX = (reverseX*10)+numstorage[araycounter];
//cout<<reverseX<<"\n";
arbcount = arbcount - 1;
araycounter = araycounter + 1;
}
abtNum = 1000000000;
numlength = 10;
sum = reverseX + originalX;
cout<<reverseX<<"\n";
cout<<sum<<"\n";
cin.get();
notpalin = ispalin(sum);
x = sum;
storagecount = 0;
araycounter = 0;
originalX = x;
reverseX = 0;
}
if(notpalin == false)
{
cout<<"palindrome found "<<sum<<"\n";
cin.get();
}
else
{
cout<<"no palindrome "<<sum<<"\n";
cin.get();
}
}