Two python solution with O(1) space


  • 6
    T

    I. reverse the number first and see if it is equal to the original number.

    def isPalindrome(self, x):
        if x < 0:
            return False
        p, res = x, 0
        while p:
            res = res * 10 + p % 10
            p /= 10
        return res == x
    

    II. find the largest power of 10 which is smaller then x first. Then check if left most digit is equal to right most digit and so on.

    def isPalindrome(self, x):
        if x < 0:
            return False
        b = 1
        while x / b >= 10:
            b *= 10
        while b >= 10:
            if x / b != x % 10:
                return False
            x, b = (x % b) / 10, b / 100
        return True

  • 0
    C

    Good solutions! In the second one, b can also be got by:

        b = 10 ** int(math.log10(x))

  • 0
    X

    Like the first answer!

    Neat.


  • 0
    K

    The first solution is awesome!
    I like it!


  • 0
    A

    @tc639
    The last line of the first solution doesn't make sense because x is still the input number. I tested both solutions above and they return false when x = 1001.


Log in to reply
 

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