LeetCode -Python [ day 3 :回文数 ]
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。
解法一:(转换成字符串)
class Solution:
def isPalindrome(self, x: int) -> bool:
if x >= 0 and int(str(x)[::-1]) == x:
return True
else:
return False
解法二:(不转换成字符串)
class Solution:
def isPalindrome(self, x: int) -> bool:
#思路:逆序求整个数每一位上的余数
#例如:121,即从 个位 到 百位 求每个位数上的余数)
if x < 0:
return False
else:
temp = 0
result = x
#while temp目的:判断当前是否还有位数需要取余
while temp:
# result*10:每次前进一位,即个位到十位到百位
#result此时会从个位开始取余,直至最后一位
result = result * 10 + temp % 10
temp //= 10
# return result == x返回bool值
return result == x