LeetCode #9: Palindrome Number
Determine whether an integer reads the same forwards and backwards — without using extra space.
The Problem
Given an integer x
, return true
if it is a palindrome, and false
otherwise.
A palindrome reads the same forwards and backwards.
Examples
Input: 121 → Output: ✅ true (Reads same forwards and backwards)
Input: -121 → Output: ❌ false (Negative numbers can't be palindromes (due to '-'))
Input: 10 → Output: ❌ false (Reads as '01' backwards → not same)
Input: 0 → Output: ✅ true (Single digit → always a palindrome)
Input: 1221 → Output: ✅ true (Even-length palindrome)
Key Insight
- Negative numbers are never palindromes because of the minus sign
- Single-digit numbers (0–9) are always palindromes
- You can reverse the number mathematically and compare
- Don’t convert to string — that uses extra space!
✅ Simple & Efficient Solution
Reverse the number digit by digit and compare with the original.
function isPalindrome(x) {
// Negative numbers and numbers ending in 0 (but not 0) can't be palindromes
if (x < 0 || (x % 10 === 0 && x !== 0)) return false;
let reversed = 0;
let temp = x;
while (temp > 0) {
reversed = reversed * 10 + (temp % 10);
temp = Math.trunc(temp / 10);
}
return reversed === x;
}
How It Works
- Reject negatives and numbers like
10
,100
(they end in 0 but aren‘t single-digit) - Reverse the number using:
digit = temp % 10
→ get last digitreversed = reversed * 10 + digit
→ build reversed numbertemp = Math.trunc(temp / 10)
→ remove last digit
- Compare reversed with original
💡 Bonus: String Approach (Not Recommended)
You can solve this in one line — but it‘s not optimal.
function isPalindrome(x) {
return x >= 0 && x.toString() === x.toString().split('').reverse().join('');
}
⚠️ Why avoid it? It uses O(d) extra space (where d = digits), and string conversion is slower.
🌍 Real-World Applications
Palindromes appear in real systems.
🔢 Data Validation
Some ID numbers, serial codes, or checksums use palindrome patterns to detect input errors.
🛡️ Security: Obfuscation Detection
Malware sometimes uses symmetric number patterns to hide in logs. Security tools scan for them.
🧩 Puzzle Games
Math-based games often include palindrome challenges — great for learning number patterns.
📡 Networking
Some protocols use symmetric sequences for synchronization or error detection.
💡 Fun Fact: The largest known palindromic prime has over 1 million digits. Checking it requires optimized math — just like our solution!
Summary
This problem teaches how to manipulate integers without converting to strings — a key skill in systems programming, embedded software, and competitive coding.