My C++ solution without extra space


  • 0
    W
    class Solution {
    public:
    	bool isPalindrome(int x) {
    		if(x < 0)return false;
    		while(x > 0){
    			if(getHead(x) != x % 10)return false;
    			if(getLength(x) - getLength(x - getHead(x) * pow(10, getLength(x))) > 1){
    				if(
    					(int)((x - getHead(x) * pow(10, getLength(x))) /10)
    					%
    					(int)pow(
    					10,
    					getLength(x) - getLength(x - getHead(x) * pow(10, getLength(x))) - 1// skip 0 nums
    					)
    					!= 0) return false;
    			}
    			x -= getHead(x) * pow(10, getLength(x));
    			x /= 10;
    			while(x && !(x % 10)){
    				x /= 10;
    			}
    		}
    		return true;
    	}
    private:
    	int getHead(int x){
    		while(x/10 > 0)
    			x /= 10;
    		return x;
    	}
    	int getLength(int x){
    		if(!x)return 0;
    		return log10(x);
    	}
    };

Log in to reply
 

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