9. Palindrome Number

题目

Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.

思路

比较简单。关于不能使用额外的空间这个要求,只要牺牲一些时间和多写点代码就能做到了。

实现

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0) return false;
        int tmp,length=0;
        tmp = x;
        while(tmp > 0){
            length++;
            tmp/=10;
        }
        for(int i=0; i<=(length-1)/2; i++){
            if(getBit(x,i)!=getBit(x,length-1-i)) return false;
        }
        return true;
    }
private:
    int getBit(int x, int index){
        for(int i=0; i<index; i++){
            x/=10;
        }
        return x%10;
    }
};

思考

看了别人写的,吐血。
只要生成其镜像数再比较即可=_=

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0) return false;
        int sum=0, y = x;
        while(x>0)
        {
            sum = sum*10+x%10;
            x = x/10;
        }
        return y == sum;        
    }
};

但是有个问题,上面的代码中,镜像后的数有可能溢出。不知道这是怎么过的,而且还是排名最靠前的的解法。可能是测试数据太简单或者当时的测试数据太简单?看来以后看别人的代码要小心了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容