力扣回文数
要求
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
思路1
1.将数字 转为字符串
2.然后遍历左半部分==右半部分 一直到中间位置
代码片
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
x=str(x)
l=len(x)
index=l-1
for i in range(l//2):
if x[i]!=x[index]:
return False
else:
index-=1
return True
思路二
1.将数字 转为字符串
2.将字符串反顺序,然后判断是否相等
代码片
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
return str(x)==str(x)[::-1]
思路二
1.将数字 转为字符串
2.根据奇数偶数判断不同的返回结果
3.两边同时判断,到中间位置
代码片
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
l=len(str(x))
if l%2==0:
return str(x)[:l//2]==str(x)[l:l//2-1:-1]
else:
return str(x)[:l//2]==str(x)[l:l//2:-1]