不使用额外空间判断整形数字是否回文

来源:互联网 发布:雨人软件 滕德润 编辑:程序博客网 时间:2024/06/04 18:21

先来个使用额外空间的简单版本,其实就是将数组转换为字符串后使用判断回文字符串的方式就行

def isPalindrome(self, x):        if x<0:            return False        x = str(x)        odd = len(x)%2        i,j = 0,0        if odd:            i = len(x)/2            j = len(x)/2        else:            i = len(x)/2            j = i-1        while i>=0 and j<len(x):            if x[i]!=x[j]:                return False            i -= 1            j += 1        return True

再来个不使用额外空间的版本


def isPalindrome(self, x):        if x<0 or (x!=0 and x%10==0):            return False        rev = 0        while rev<x:            rev = rev*10 + x%10            x = x/10        return x==rev or x==rev/10


原创粉丝点击