πŸ” Palindrome Number in JavaScript


πŸ” Palindrome Number in JavaScript

A palindrome is a word, phrase, or number that reads the same forward and backward.

✨ Examples:

  • Words: madam, level, radar

  • Numbers: 121, 1331, 444

Numbers like 123 or -121 ❌ are not palindromes.


🧩 Problem Statement

πŸ‘‰ Write a function that checks whether a number is a palindrome.

  • Input: 121

  • Output: true βœ… (because reading it backwards still gives 121)


πŸ–₯️ Solution Approach

We’ll solve it using math (without converting to string) πŸš€

Steps:

  1. If the number is negative β†’ directly return false (since -121 β‰  121-).

  2. Store a copy of the number (xCopy).

  3. Reverse the digits of the number.

    • Use % 10 to extract last digit.

    • Multiply the reversed number by 10 and add the last digit.

    • Use Math.floor(n / 10) to remove the last digit.

  4. Compare reversed number with original copy.

    • If equal β†’ it’s a palindrome.

    • Else β†’ not a palindrome.


πŸ§‘β€πŸ’» Code Implementation

function isPalindrome(x) {
    // Step 1: Handle negatives
    if (x < 0) return false;

    // Step 2: Copy number
    let xCopy = x;
    let rev = 0;

    // Step 3: Reverse digits
    while (x > 0) {
        let rem = x % 10;             // last digit
        rev = (rev * 10) + rem;       // add to reversed
        x = Math.floor(x / 10);       // remove last digit
    }

    // Step 4: Compare
    return rev === xCopy;
}

πŸ” Dry Run Example

πŸ‘‰ Input: 121

StepxremrevExplanation
Init121β€”0Start
11211rev = 0*10+1 β†’ 1
21212rev = 1*10+2 β†’ 12
301121rev = 12*10+1 β†’ 121

Finally β†’ rev(121) === xCopy(121) βœ… Palindrome!


🎯 Test Cases

console.log(isPalindrome(121));   // true
console.log(isPalindrome(-121));  // false (negative numbers not palindromes)
console.log(isPalindrome(10));    // false (reverse = 01 β†’ 1)
console.log(isPalindrome(1331));  // true
console.log(isPalindrome(123));   // false

πŸ› οΈ Alternate Approaches

  1. Convert to String

     function isPalindromeStr(x) {
       let str = x.toString();
       return str === str.split("").reverse().join("");
     }
    

    βœ… Short and simple, but less efficient (extra memory used).

  2. Two-pointer technique on string
    Compare first and last characters, then move inward.


πŸ“Œ Key Takeaways

  • Palindrome check is a common coding interview problem.

  • Avoiding string conversion shows stronger algorithmic skills.

  • Practice variations:

    • Palindrome strings

    • Palindrome with spaces/ignoring cases ("A man a plan a canal Panama")


✨ You now have a clear understanding of how to check palindrome numbers in JavaScript β€” both mathematically and using strings.

0
Subscribe to my newsletter

Read articles from Kamlesh Choudhary directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Kamlesh Choudhary
Kamlesh Choudhary