Tuesday, July 15, 2014

[LeetCode] Palindrome Number

Problem Statement (link):
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.
Analysis:
The hints rule some straightforward ideas you may get.

Generically, we would look at the first (MSB) and the last digit (LSB) of an integer to determine if it's palindrome, then move on to the second MSB and second LSB, and so on... We could implement this method directly.

In the following method, I remove the MSB and LSB each time I compare them, so that every time I only need to look at the MSB and LSB of the updated integer.

Code:
class Solution {
public:
    bool isPalindrome(int x) {
        if (x<0) return false;
        // get num length
        int len=1, t=x;
        while(t/10>=1) {
            t/=10;
            len++;
        }

        // compare first and last digit
        while(x>0) {
            int d=pow(10,len-1);
            if (x%10!=x/d)
                return false;
            int t=x%d;
            x=(t-t%10)/10;
            len-=2;
        }

        return true;
    }
};

No comments:

Post a Comment