Monday, February 9, 2015

9 Palindrome Number

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

Solution 1: Use String
class Solution {
public:
    bool isPalindrome(int x) {
        if (x<0)
            return false;
        if (x==0)
            return true;
        string original = to_string(x);
        string reverse;
        while(x>0)
        {
            reverse.push_back(x%10 + '0');
            x /= 10;
        }
        return reverse == original;
    }
};
Solution 2: Use integer
class Solution {
public:
    bool isPalindrome(int x) {
        if (x==0)
            return true;
        if (x<0|| x%10==0)
            return false;
        
        int y = 0;
        while(x>y)
        {
            y = y*10 + x%10;
            if (x==y)
                return true;
            x /= 10;
        }
        return x==y;
    }
};

No comments:

Post a Comment