0
点赞
收藏
分享

微信扫一扫

leetcode题目9:回文数

题目描述

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例:

输入: 121
输出: true

解法

解法一:数字转字符串

class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
else:
y = str(x)[::-1]
if y == str(x):
return True
else:
return False

解法二:纯数学计算

class Solution:
def isPalindrome(self, x: int) -> bool:
if x>=0:
y = self.inverse(x)
print(f"y:{y}")
if y == x:
return True
else:
return False
else:
return False

def inverse(self, num):
i = 0
num1 = num
while True:
if num1//10==0:
break
i += 1
num1 = num1//10
sum = 0
while i>= 0:
sum = sum + (num%10) * (10**i)
num = num // 10
i = i -1
return sum


举报

相关推荐

0 条评论