【C++】判断一个数是不是回文数,不使用额外的空间

题目描述:Determine whether an integer is a palindrome. Do this without extra space.

方法一:将整数转换成字符串,然后用前后两个指针,来判断是不是回文。代码如下:

bool isPalindrome(int x) {

    if(x<0)
        return false;
    int length=0,temp=x;
    while(temp){
        length++;
        temp/=10;
    }
    //一个特殊的情况是x==0
    if(x==0)
        length++;
    char str[length];
    //考虑到题目要求不能使用额外的空间,不知这样使用sprintf函数会不会占用多余的空间
    sprintf(str,"%d",x);
    cout<<"s:"<<str<<"  "<<length<<endl;
    int i=0,j=length-1;
    while(i<=j){
        if(str[i]!=str[j])
            return false;
        if(str[i]==str[j] && i<=j){
            i++;
            j--;
        }
    }
    if(i>=j)
        return true;
}

由于方法一中使用了sprintf来将整数转换成字符串,不知这个函数是否会使用额外的空间。方法二是完全使用除法运算,空间复杂度为O(1):

bool isPalindrome2(int x) {
    if(x<0)
        return false;
    int length=0,temp=x;
    while(temp){
        length++;
        temp/=10;
    }
    if(length==1)
        return true;
    int half_len = length/2;
    int frontNum=0,rearNum=0,divisor=1;
    temp=x;
    for(int i=0;i<half_len;i++){
        divisor*=10;
        rearNum=rearNum*10+temp%10;
        temp=temp/10;
    }
    if(length%2==1)
        divisor*=10;
    frontNum=x/divisor;
    if(frontNum==rearNum)
        return true;
    else
        return false;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一杯拿铁go

你的打赏是我更新最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值