Palindrome Number
LeetCode 9 · Easy · solution, intuition & step-by-step walkthrough
Reverse half the digits and compare.
This is how I solved Palindrome Number (LeetCode 9), an easy problem from the Other pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Reverse only the second half of the number and compare it with the first half. Stop when the reversed part is no longer smaller than what's left; for odd lengths, drop the middle digit with // 10.
Approach
- 1
Negatives and numbers ending in 0 (except 0) aren't palindromes.
- 2
Move digits from x onto reversed until reversed ≥ x.
- 3
Compare x with reversed or reversed // 10.
How I solved it
Half reversalPythonO(log x) time
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0 or (x!=0 and x%10==0):
return False
#121
#reverse from right till middle is same return true
reversed = 0
while x>reversed:
reversed = reversed*10+x%10
x = x//10
return True if reversed == x or reversed//10 == x else False
#12321 12, 12, for odd length revesrsed will be 123, so if we devide 123/10 we will get 12Palindrome Number — FAQ
What is the intuition behind Palindrome Number?
Reverse only the second half of the number and compare it with the first half. Stop when the reversed part is no longer smaller than what's left; for odd lengths, drop the middle digit with // 10.
How do you solve Palindrome Number (LeetCode 9)?
1. Negatives and numbers ending in 0 (except 0) aren't palindromes. 2. Move digits from x onto reversed until reversed ≥ x. 3. Compare x with reversed or reversed // 10.
What is the time and space complexity of Palindrome Number?
Time: O(log x). Space: O(1). (Accepted approach: Half reversal.)
What are common mistakes in Palindrome Number?
Converting to a string works but isn't the intended trick.