LeetCode题目:Palindrome Number

By | 2012 年 10 月 16 日

Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
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.



方法就是不断地取第一位和最后一位(10进制下)进行比较,相等则取第二位和倒数第二位,直到完成比较或者中途找到了不一致的位。
难点在于输入的数会很大,超过了int32的表示范围。而在测试机器上,int和long都是32位的,long long才是64位。



代码,240ms过大集合

class Solution {
public:
    bool isPalindrome(int x) {
        //cout<<sizeof(long long);
        if(x < 0)
            return false;
        long long xx = x;
        long long s = 1;
        while(xx / s)
            s *= 10;
        s /= 10;
        long long e = 10;
        //if(s < e) cout<<s<<"vs"<<e<<"forx"<<x;
        while(s >= e) {
            long long sd = (xx / s);
            long long ed = (xx % e) / (e / 10);
            if(sd!=ed) {
                //cout<<sd<<"vs"<<ed<<"at"<<s;
                return false;
            }
            //cout<<sd<<"vs"<<ed<<"at"<<s;
            xx = xx % s;
            s /= 10;
            e *= 10;
        }
        return true;
    }
};

5 thoughts on “LeetCode题目:Palindrome Number

  1. Pingback: Leetcode: Palindrome Number – uniEagle

    1. uniEagle Post author

      有道理,我理解的extra space是堆上的空间,不过如果把局部变量也算上的话,我想这个题也是可以做的,可以用计算来替换这些局部变量。

      Reply

发表评论

电子邮件地址不会被公开。 必填项已用*标注