No extra space but only one additional integer to record the length in Python


  • 0
    C

    Since it requires no extra space using to solve this problem, we can't convert the input number into string or List, or adding a copy of input number (it will cost extra space when the input number is very big). In my solution, only using one integer to record the length/bits of input number, but it costs 290ms to get the result.
    Any suggestions to this answer to improve the efficiency?

    class Solution:
        # @param {integer} x
        # @return {boolean}
        def isPalindrome(self, x):
            if x < 0:
                return False
            
            if x < 10:
                return True
            
            cnt = 1
            while (x / (10 ** cnt)):
                cnt += 1
            
            for bit in xrange(cnt / 2):
                if ((x / (10 ** (cnt - 1 - bit))) % 10) == ((x % 10 ** (bit + 1)) / 10 ** (bit)):
                    continue
                else:
                    return False
            return True

Log in to reply
 

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