Leetcode #9 — Palindrome Number (Python)

Dhairya Dave
2 min readDec 26, 2020

Hello everyone, today we’ll be looking at the Palindrome Number problem. This question is marked as “Easy” on Leetcode.

Problem Statement

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?

Examples from Leetcode

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

Solution (converting the int to a string)

Submission on Leetcode:

Explanation (with two examples):

1. Let's call: isPalindrome(11211)- Since 11211 > 0, we check the following:str(x)[::-1] == str(x)str(11211)[::-1] ->'11211'[::-1] -> '11211'
str(11211) = '11211'
and '11211' == '11211' -> True. As a result, True is returned.2. Let's call: isPalindrome(-10)- Since -10 < 0, False is returned.

Solution (without converting the int to a string)

Submission on Leetcode:

Explanation (with two examples):

1. Let's call: isPalindrome(121)- Since 121 > 0, set y = 0 and temp = x = 121- Iteration 1:while temp (121) -> True ... then,y = (y * 10) * (temp % 10) = (0 * 10) * (121 % 10) = 1
temp //= 10 = 12
- Iteration 2:while temp (12) -> True ... then,y = (y * 10) * (temp % 10) = 12
temp //= 10 = 1
- Iteration 3:while temp (1) -> True ... then,y = (y * 10) * (temp % 10) = 121
temp //= 10 = 0
- Since temp = 0, the while loop terminates and we check:x == y -> 121 == 121 -> TrueTrue is returned.
2. Let's call: isPalindrome(-100)- Since -100 < 0, False is returned.

That’s all, folks! Happy learning!

Dhairya Dave

--

--

Dhairya Dave
Dhairya Dave

No responses yet