C++ simple solutions


  • 1
    Z
    class Solution {
    public:
    bool isPalindrome(int x) {
        //return solution1(x);  //no extra space but runtime not stable
        //return solution2(x);    //with int's but runtime stable
        //return solution3(x);    //with int's but runtime stable
        return solution4(x);    //with int's but runtime stable
    }
    private:
    bool solution1(int x){
        if(x < 0) return false;
        if(x / 10 == 0) return true;
        if(x % 10 == 0) return false;
        int dig = getNumOfDig(x);
        for(int i = 1; i <= dig / 2; i++)
            if((x/(int)pow(10, i - 1)%10 != (x/(int)pow(10, dig - i))%10))
                return false;
        return true;
    }
    bool solution2(int x){
        if(x < 0) return false;
        if(x / 10 == 0) return true;
        if(x % 10 == 0) return false;
        int dig = getNumOfDig(x);
        int left = pow(10, dig - 1);
        int right = 1;
        dig /= 2;
        for(int i = 1; i <= dig; i++){
            if((x / left) % 10 != (x / right) % 10)
                return false;
            left /= 10;
            right *= 10;
        }
        return true;
    }
    bool solution3(int x){
        if(x < 0) return false;
        if(x / 10 == 0) return true;
        if(x % 10 == 0) return false;
        int left = 10;
        while(x/left >= 10) left *= 10;
        int right = 1;
        while(left > right){
            if((x / left) % 10 != (x / right) % 10)
                return false;
            left /= 10;
            right *= 10;
        }
        return true;
    }
    bool solution4(int x){
        if(x < 0) return false;
        if(x / 10 == 0) return true;
        if(x % 10 == 0) return false;
        int tmp = 0;
        while(x > tmp){
            tmp = tmp * 10 + x % 10;
            if(x == tmp) return true;   //case odd digits
            x /= 10;
        }
        return x == tmp;    //case even digits
    }
    int getNumOfDig(int x){
        if(x == 0) return 0;
        return 1 + getNumOfDig(x / 10);
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.