My accepted code in C++ with time complexity o(N)


  • 0
    C
    class Solution {
    public:
        bool isPalindrome(int x) {
    		int left = 1000000000; //the MAX int is 2147483647
    		int right = 10;
            if (x < 0)
    		{
    			return false;
    		}
    		else if (x <= 9)
    		{
    			return true;
    		}
    		
    		while (true)
    		{
    			if (0 == x / left)
    			{
    				left /= 10;
    				continue;
    			}
                //see if the left hand side digit is equal to the right hand side one
    			if (((x / left) % 10) != (x % right) / (right / 10)) 
    			{
    				return false;
    			}
    			left /= 10;
    			right *= 10;
    			if (left < right)
    			{
    				break;
    			}
    		}
    		return true;
        }
    };
    

    From my point of view, "without extra space" only means we should not allocate variables to store the digits of parameter int x. I only allocate two variables left and right just work as an indicator flag, so I think this solution satisfy the question's restriction.


Log in to reply
 

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