The problem is as follows:
Given an integer x, return true if x is a palindrome, and false otherwise.
Example 1:
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
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:
Output: false
Explanation: Reads 01 from right to left. Therefore, it is not a palindrome.
Here is how I solved it:
Let’s convert the given integer into a string
In Python we can reverse a string by slicing: create a slice that starts at the end of the string and moves backwards. The slice statement [::-1] means start and end of the string and end at position 0, move with the step -1, which means one step backwards. https://www.w3schools.com/python/python_howto_reverse_string.asp
Let’s compare the reversed string to the given integer (again, convert it to string: we can only compare same datatypes). Return True if it matches, else False.
return True
return False
But hey, we can actually write just one line of code using ternary operator! To be honest, I am not sure if it’s bad design, but it seemed more readable to me.
Here is the complete solution:
def isPalindrome(self, x: int) -> bool:
return True if str(x)[::-1] == str(x) else False