[Leet Code] Palindrome Number

Matthew Boyd
2 min readJan 20, 2021

--

Leetcode: https://leetcode.com/problems/palindrome-number/

Problem:

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Follow up: Could you solve it without converting the integer to a string?

Example 1:

Input: x = 121
Output: true

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.

Example 4:

Input: x = -101
Output: false

Constraints:

  • -231 <= x <= 231 - 1

Solution:

class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""

stringX = str(x)
if "-" in stringX:
return False
else:
reverse = list(stringX)
reverse.reverse()
return list(stringX) == reverse

Explanation:

First of all, we turn the integer we’re given into a string, as this will be easier to manipulate. Then we check if there is a “-” sign in there, that would mean that it’s automatically not a palindrome. Then if it contains “-”, then we return False, otherwise, we turn the string into a list and reverse it, and compare it against the input as a list and if this is equal, it’ll be true, otherwise, it’ll be false.

--

--

Matthew Boyd
Matthew Boyd

Written by Matthew Boyd

Learning, and posting my findings!

No responses yet