sourcecode

Monday, February 23, 2015

Palindrome Number

//not the best

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        string s = "";
        while(x > 0) {
            int dig = x % 10;
            x /= 10;
            s.push_back(dig);
        }
        for(int ii = 0; ii < s.size(); ++ii){
            int jj = s.size()-1-ii;
            if (s[ii] != s[jj]) return false;
        }
        return true;
    }
};


// better, without extra space
class Solution {
public:
    bool isPalindrome(int x) {
        if (x == 0 ) return true;
        if (x < 0 || x / 10 * 10 == x) return false;
        int mirror = 0;
        while (mirror < x) {
            int dig = x % 10;
            mirror = mirror * 10 + dig;
            if (mirror == x) return true;
            x /= 10;
            if (mirror == x) return true;
        }
        return false;
    }
};

No comments: