9. 回文数
解题思路:这道题有两种解法。1、常规的解法就是将输入的整形数转换为字符串,再将字符串进行反转,之后与原数进行判断。2、第二种方法是采用数学的方法。方法为逐次整除,将余数提取出来带入,重新组建数字,不断乘以10去加上新算出的余数,如果是回文数字,那么新组建的数字就和输入的一样。
方法一代码如下
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
x = str(x)
x1 = x[::-1]
if x == x1 :
return True
else:
return False
方法二代码
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x > 0:
n,newed = 0,0
n = x
while x > 0:
newed = newed *10 + x % 10
x = x//10
if newed == n:
return True
else:
return False
elif x == 0:
return True
elif x < 0:
return False
看了第一名的代码不得不佩服是大佬,请欣赏大佬的表演
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
else:
return int(str(x)[::-1]) == x