
Given an integer x, return true if x is a palindrome, and false otherwise.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -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: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-231 <= x <= 231 - 1
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
else:
str_x = list(str(x))
for i, ch in enumerate(str_x):
if str_x[-1 * (i + 1)] != ch:
return False
return True
I divided it for two cases.
And we need to check only half of the whole digits.
OMG🤦♀️.. I forgot how to change int to string that I used string() at first.
a = 123 # int
str_a = str(a) # string '123'
b = 12.3 # float
str_b = str(b) # string '12.3'
# also possible to use
str_a = f"{a}"
class Solution:
def isPalindrome(self, x: int) -> bool:
# literally comparing with reversed x,
# which is definition of palindrome!
return str(x)==str(x)[::-1]
I have to know how to use basic grammar of python (like index) more.