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

来源:互联网 发布:怎样看待网络流行语 编辑:程序博客网 时间:2024/05/17 04:20

题目描述: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;}
原创粉丝点击