Determine whether an integer is a palindrome. Do this without extra space.
这道题不能用额外的空间,还有第一步先要把负数排除。
#include<stdio.h>
#define bool char
#define true 1
#define false 0
bool isPalindrome(int x)
{
int temp,num=0,i,j,k,flag=1,y,z,temp1,temp2;
temp=x;
if(temp<0)//首先排除负数不是回文数
return false;
while(temp)
{
temp=temp/10;
num++;
}
if(!(num%2))//偶数
{
for(i=1;i<=num/2;i++)
{
temp1=x;
temp2=x;
j=i;
k=num-i;
while(j-1)
{
temp1=temp1/10;
j--;
}
y=temp1%10;
while(k)
{
temp2=temp2/10;
k--;
}
z=temp2%10;
if(y!=z)
{
flag=0;
break;
}
}
}
else//奇数
{
for(i=1;i<(num+1)/2;i++)
{
temp1=x;
temp2=x;
j=i;
k=num-i;
while(j-1)
{
temp1=temp1/10;
j--;
}
y=temp1%10;
while(k)
{
temp2=temp2/10;
k--;
}
z=temp2%10;
if(y!=z)
{
flag=0;
break;
}
}
}
if(flag)
return true;
else
return false;
}
int main()
{
int x;
bool a;
scanf("%d",&x);
a=isPalindrome(x);
printf("%d\n",a);
return 0;
}
上面是我自己写的,通过了但是代码太长了,不整洁,自己看了都嫌弃,后来看看别人写的,服!
#include<stdio.h>
#define bool char
#define true 1
#define false 0
bool isPalindrome(int x)
{
int y,z,len,flag=1;
if(x<0)
return false;
for(len=1;(x/len)>=10;len=len*10);
while(x)
{
y=x/len;
z=x%10;
if(y!=z)
{
flag=0;
break;
}
x=(x%len)/10;
len=len/100;
}
if(flag)
return true;
else
return false;
}
int main()
{
int x;
bool a;
scanf("%d",&x);
a=isPalindrome(x);
printf("%d\n",a);
return 0;
}