- 转换为字符串,将字符串翻转,如果翻转前后字符串相等,则返回True,否则返回False。
- 转换为字符串,循环字符串长度的一半,逐个判断字符串的首尾是否相等。若有一个不相等,则返回False,否则,返回True。
- 对整数不断除以10,不断取余数,然后对余数不断乘以10,直到最初的整数为0。然后判断最初的数和最终通过余数生成的数是否相等,若相等,则返回True,若不相等,则返回False。
- 代码1
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
return str(x) == str(x)[::-1]
- 代码2
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
x = str(x)
length = len(x)
for i in range(length//2):
if x[i]!=x[length-i-1]:
return False
return True
- 代码3
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
first_num = x
res = 0
while(x>0):
res = res*10+x%10
x =x//10
if (res == first_num):
return True
else:
return False
4.编写验证过程中的完整代码
只要给上述代码后面加上如下几行,即可输出验证。由于过于基础,此处就不再赘述,可以参考我本专栏其他较早博客的写法。
solution = Solution() print(solution.isPalindrome(123456)) print(solution.isPalindrome(121))
拒绝内耗,永远心存善念。
不要恐惧,只管向前就好。



