Leetcode Day 2: Palindrome Number

The problem is as follows:
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.
Enter fullscreen mode
Exit fullscreen mode

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.
Enter fullscreen mode
Exit fullscreen mode

Example 3:

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore, it is not a palindrome.
Enter fullscreen mode
Exit fullscreen mode

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
rev = str(x)[::-1]
Enter fullscreen mode
Exit fullscreen mode
  • 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.
if rev == str(x): return True
return False
Enter fullscreen mode
Exit fullscreen mode

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:

class Solution: def isPalindrome(self, x: int) -> bool: return True if str(x)[::-1] == str(x) else False
Enter fullscreen mode
Exit fullscreen mode

Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Since the area of email marketing is continually evolving, email marketer must manage numerous issues. Ios app development.