Back to course

Problem: Palindrome Number

Content Reader1 words • 0:00 • Browser TTS

image.png

Introduction to DSA & Problem Solving – Problem: Palindrome Number

Problem Statement

Write a function isPalindrome(x) that takes an integer x and returns true if it reads the same backward and forward; otherwise, returns false.

Requirements

  • Must handle both positive and negative integers.
  • Return false for negative numbers (since -121121-).

Constraints

MetricComplexity
Time ComplexityO(d) — where d is the number of digits
Space ComplexityO(1) — uses constant space

Examples

InputOutputExplanation
121trueReads the same backward and forward
-121falseNegative sign makes it non-palindromic
10falseReverse is 01 which ≠ 10

Step-by-Step Approach

  1. Handle Negatives
    If x < 0, return false.
  2. Store Original Value
    Keep a copy of the original number → xCopy = x.
  3. Reverse the Number
    • Initialize rev = 0
    • While x > 0:
      • rem = x % 10
      • rev = rev * 10 + rem
      • x = Math.floor(x / 10)
  4. Compare Values
    • If rev === xCopy, return true
    • Otherwise, return false

Visualization

x = 121
rev = 0

Step 1 → rem = 1, rev = 0 * 10 + 1 = 1
Step 2 → rem = 2, rev = 1 * 10 + 2 = 12
Step 3 → rem = 1, rev = 12 * 10 + 1 = 121

rev === xCopy → 121 === 121 → true

Flowchart

image.png

JavaScript Code

var isPalindrome = function(x) {
  
  // Handle Negatives
  if (x < 0) return false;
  
  // Store Original Value
  let xCopy = x;
  let rev = 0;
  
  // Reverse the Number
  while (x > 0) {
    let rem = x % 10;
    rev = rev * 10 + rem;
    x = Math.floor(x / 10);
  }
  
  // Compare Values
  return rev === xCopy;
};

console.log(isPalindrome(121)); // true

Key Takeaways

  • Negative integers can never be palindromes.
  • Efficient O(1) space and O(d) time.
  • Works purely mathematically—no string conversion needed.
Photo of Rahul Aher

Written by Rahul Aher

I'm Rahul, Sr. Software Engineer (SDE II) and passionate content creator. Sharing my expertise in software development to assist learners.

More about me