Python 222ms without using extra space ( no str() )


  • 0
    M
    class Solution(object):
        def isPalindrome(self, x):
            """
            :type x: int
            :rtype: bool
            """
            if x < 0:
                return False
            dig = 0
            temp = x
            while temp != 0: # compute number of digits first
                temp //= 10
                dig += 1
            for i in range(dig // 2): # compare 2 digits at one time
                if (x // 10 ** i) % 10 != (x // 10 ** (dig - i - 1)) % 10:
                    return False
            return True
    

    Because the description says that we may not allocate extra space, including convert x to string, so I think this might be a better way to do this problem.


Log in to reply
 

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