Palindrome Number Check
๐ Problem Statement
Given an integer, determine if it is a palindrome. An integer is a palindrome if it reads the same forward and backward. For example, 121 is a palindrome; -121 and 10 are not. Return True or False.
๐ก Intuition
Just like reversing a number, we extract digits one by one using modulo. We don't need to fully reverse the number โ we can compare the reversed number to the original. Negative numbers are never palindromes (due to the plus sign), and numbers ending in 0 (except 0 itself) are never palindromes.
๐ง Approach
- Return False immediately for negative numbers.
- Return False for numbers that end in 0 but aren't 0 themselves.
- Extract digits one at a time to build
reversed_num. - Compare
reversed_numwith the originalnโ if equal, it's a palindrome.
โก Complexity Analysis
โ number of digits in
โ only integer variables
โ ๏ธ Common Mistakes
- Converting to a string (
str(n) == str(n)[::-1]) โ valid but not a true mathematical solution - Not handling negative numbers: they have a
-prefix so can never be palindromes - Not handling numbers ending in 0:
10reversed is01 = 1, not10, so it's not a palindrome
๐ฏ Final Thoughts
This builds directly on Day 1 (Reverse Number). A palindrome check is a reversal check โ the reversed number equals the original. The early exits for negatives and trailing zeros make the solution more robust.