Instagram
youtube
Facebook
Twitter

Palindrome Number Leetcode Solution

In this tutorial, we are going to solve the Palindrome Number problem from leetcode in python.

Task:

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

Solution:

class Solution:
    def isPalindrome(self, x: int) -> bool:
        str_x = str(x)
        m = len(str_x)
        lst = []
        for i in range(m):
            idx = str_x[i]
            lst.append(idx)
        new_str = ''
        for i in lst[::-1]:
            new_str += i        
        return new_str == str_x

Steps:

step1: firstly, we made a string of our given integer (changing its type).

step2: then, we made a variable to store the length of the string.

step3: Now in a loop in the range of length of the string we append each character of the string.

step4: Now, in the new empty string we add the elements of the list but reversely.

step5: then, we return if it is the same as the previous one or not.