DEV Community

Simona Cancian
Simona Cancian

Posted on

Leetcode Day 2: Palindrome Number Explained

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay