palindrome problem

I wrote a function that takes an integer as a parameter and returns a Boolean variable stating that whether that number is a palindrome or not...

here is the code for the function..

bool IsPalindrome(int number)
{
int digits=0; int n=number;

bool equal=true;

for (int pwr=1; number/pwr>0; pwr=pwr*10)
digits=digits+1;

pwr=pwr/10;

for (int i=0; i<digits/2 && equal; i++)
{
if (number/pwr!=n%10)
equal=false;

n=n/10;
number=number%pwr;
pwr=pwr/10;
}

return equal;
}

Now it works for every number till having maximum 9 digits.. when I gave 1234554321 or 1111551111 (having 10 digits), the function returns false.. it should not!, I dont know what is going wrong...

I have check the range of the 'int' type variable, its from -2147483648 to 2147483647, the maximum number is of 10 digits and my inputs are within the range of the data type... I have no idea what is going wrong...

help me identify this error!

The error is because your variable pwr is exceeding ten digits when you calculate the number of digits. BTW, you should not declare pwr in a loop.

Better to count the digits first, then initialize pwr.

Hope this helps.
i don't see the need for all the math, this is a simple example that returns bool t/f for chars/ints
1
2
3
4
5
6
7
8
bool IsPalindrome(char text[])
{
	int len=strlen(text)-1;
	for(int x = 0,y = len;x<(int)len/2;x++,y--)
		if(text[x]!=text[y])
			return 0;
	return 1;
}
Topic archived. No new replies allowed.