我想您正在解决LeetCode 9,为此解决方案将通过:
class Solution:
def isPalindrome(self, x):
if x < 0 or (x > 0 and not x % 10):
return False
return str(x) == str(x)[::-1]
或类似于您的方法(针对后续问题):
class Solution:
def isPalindrome(self, x):
if x < 0 or (x and not x % 10):
return False
summation = 0
while x > summation:
summation *= 10
summation += x % 10
x //= 10
return x == summation or x == summation // 10
class Solution:
def isPalindrome(self, x):
if x < 0:
return False
divisor = 1
while x // divisor >= 10:
divisor *= 10
while divisor > 1:
left, x = divmod(x, divisor)
x, right = divmod(x, 10)
if left != right:
return False
divisor //= 100
return True
引用文献
有关更多详细信息,请参见Discussion Board。那里有许多公认的解决方案,解释,使用多种语言的有效算法以及时空复杂度分析。