9. Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

这道题思路挺简单的,就依次判断首尾两位即可,因为个位数肯定是对称的,所以 x 只剩一位的时候退出循环就好了。
bool isPalindrome(int x) {
    if(x < 0) return 0;
    int p = x,q = 1;
    while(p / 10){
        q *= 10;
        p /= 10;
    }
    while(1){
        if(q == 0 || x < 10) break;
        if(x % 10 != x / q)  return 0;
        x %= q;
        x /= 10;
        q /= 100;
        printf("%d %d\n",x,q);
    }
    return 1;
}
但是一提交就报错了,比如 1000021 ,由于左边存在多个0,第二步的时候就变成 2 了,这样就会被判对。还有这种情况 1001001,为了解决这些情况,我的想法
是对于下个左边的数字为0的时候,看左边下个数字是不是 0 ,如果不是返回 false,如果是就把两边的 0 都去掉,但是这样程序太麻烦了,我
写成了这样,可是结果还是不对。。。
bool isPalindrome(int x) {
    if(x < 0) return 0;
    int p = x,q = 1;
    while(p / 10){
        q *= 10;
        p /= 10;
    }
    while(1){
        if(q == 0 || x < 10) break;
        if(x % 10 != x / q)return 0;
        int next = (x / (p / 10)) % 10;
        if(!next){
            int t 
            while(!next){
                if((x / 10) % 10) return 0;
                x /= 10;
                next = (x / (p / t)) % 10;
                t *= 10;
            }
            continue;
        }
        x %= q;
        x /= 10;
        q /= 100;
        printf("%d %d\n",x,q);
    }
    return 1;
}

看了别人的代码,恍然大悟,只需要把循环的退出条件改为  x == 0 就可以了,不用担心里面存在 0 的情况,如果左边存在若干个 0 ,那么由于  x 的下一次循环的值的位数肯定是小于 p 的,差的位数就是左边 0 的个数,这样的话下次计算出来的首位会保持为 0 ,直至与 p 位数相等,相当于一直拿 0 跟末位比较,最终就是我们想要的结果。

修改之后的代码如下:

bool isPalindrome(int x) {
    if(x < 0) return 0;
    int p = 1;
    while(x / p >= 10) p *= 10;
    while(x){
        if(x / p != x % 10) return 0;
        x = (x % p) / 10;
        p /= 100;
    }
    return 1;
}





posted @ 2018-03-29 23:03  ACLJW  阅读(143)  评论(0编辑  收藏  举报