Leetcode: Palindrome Number

Problem

Leetcode link for this question
Determine whether an integer is a palindrome. Do this without extra space.

Analyze

This is the previous post on this question
This is easy question, just find the most left digit and then compare each digit from left-right ends to center.

Code

C++ code accept by Leetcode, which exclude negative number like -121 as palindrome

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0)
            return false;
        int highDigit = 1;
        while(x / highDigit >= 10)
            highDigit *= 10;
        int lowDigit = 1;
        while(highDigit > lowDigit){
            int high = (x / highDigit) % 10;
            int low = (x/lowDigit) % 10;
            if(high != low)
                return false;
            highDigit /= 10;
            lowDigit *= 10;
        }
        return true;
    }
};

C++ code for who consider negative number like -121 also as palindrome

class Solution {
public:
    bool isPalindrome(int x) {
        int highDigit = 1;
        while(x / highDigit >= 10 || x / highDigit <= -10)
            highDigit *= 10;
        int lowDigit = 1;
        while(highDigit > lowDigit){
            int high = (x / highDigit) % 10;
            int low = (x/lowDigit) % 10;
            if(high != low)
                return false;
            highDigit /= 10;
            lowDigit *= 10;
        }
        return true;
    }
};

LeetCode题目:Palindrome Number

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;
    }
};