Problem description
Determine 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.
Solution
成对比较头尾对应index的字符是否相等即可
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0:
return False
x = str(x)
l = len(x)
for i in range(0,int(l/2)):
if x[i] is not x[l-i-1]:
return False
return True
不将整数转换成字符串的方法:
通过求余数的方法将整数进行反转,并将反转后的数字与原输入进行对比:
def isPalindrome(self, x: int) -> bool:
if x<0:
return False
temp=x
rev=0
while(x>0):
digit=x%10
rev=rev*10+digit
x=x//10
if temp==rev:
return True
else:
return False