9. Palindrome Number

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值