6 lines python code, without extra space, just use param x


  • 0
    S
    1. find the middle index of x, 123 middle number is 2 and middle index is 1; 1234 middle number is 23 and middle index is 2.
    2. if x is 121 should return 12 == 21, if x is123321 should return 123 == 321, slice from middle index.
    3. we can transform int to str to use len() find the length of x then retransform str to int.
    4. I use python slice feature to reverse the string, b = '123' then b[::-1] is 321
    5. the testcases show me the nagative number always return false. (even if I disagree :( )
    class Solution(object):
        def isPalindrome(self, x):
            """
            :type x: int
            :rtype: bool
            """
            if x < 0:
                return False
            if len(str(x)) % 2 == 0:
                return int(str(x)[:len(str(x))//2]) == int(str(x)[len(str(x))//2:][::-1])
            else:
                return int(str(x)[:len(str(x))//2+1]) == int(str(x)[len(str(x))//2:][::-1])
    

Log in to reply
 

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