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.
Follow up:Coud you solve it without converting the integer to a string?
my solution:
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0: return False
l = []
while x > 0:
l.append(x % 10)
x = x // 10
l_copy = l.copy()
l.reverse()
if l == l_copy:
return True
else:
return False
AustinBaird12's solution:
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
y = str(x) # Convert input to a String
z = y[::-1] # Save another string as the reversed input
if y == z:
return True
else:
return False
# By nature of palindromes, if the original string it exactly the same
# as the reversed string, it is by definition a Palindrome.
uchaan's solution:
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
stx=str(x)
rvstx=''.join(reversed(stx))
return (stx==rvstx)
最简洁版 from CodingKido:
return (str(x)==str(x)[::-1])
网友评论