题目
whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
m
解答
如果可以转成str的话,那就比较容易
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0:
return False
x = str(x)
if len(x)==1:
return True
left, right = 0, len(x)-1
while left<=right:
if x[left] != x[right]:
return False
left += 1
right -= 1
return True
如果不能转成str的话,就一边求出每一位上的数字,一边算反过来之后的数字
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0:
return False
num = x
ret = 0
while num != 0:
ret = ret*10+num%10
num //=10
return ret==x





近期评论