Back to LeetCode Series

LeetCode #9: Palindrome Number

Determine whether an integer reads the same forwards and backwards — without using extra space.

Difficulty: EasyPattern: Math, Two PointersTime: 5 min read

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: 121Output: ✅ true  (Reads same forwards and backwards)

Input: -121Output: ❌ false  (Negative numbers can't be palindromes (due to '-'))

Input: 10Output: ❌ false  (Reads as '01' backwards → not same)

Input: 0Output: ✅ true  (Single digit → always a palindrome)

Input: 1221Output: ✅ 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.

js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

  1. Reject negatives and numbers like 10, 100 (they end in 0 but aren‘t single-digit)
  2. Reverse the number using:
    • digit = temp % 10 → get last digit
    • reversed = reversed * 10 + digit → build reversed number
    • temp = Math.trunc(temp / 10) → remove last digit
  3. Compare reversed with original

💡 Bonus: String Approach (Not Recommended)

You can solve this in one line — but it‘s not optimal.

js
1
2
3
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.

View All Challenges