Palindrome Number

(#9), Easy

Category: Math

Problem Statement

Given an integer `x`, return `true` if `x` is a palindrome, and `false` otherwise. A palindrome is a number that reads the same backward as forward. Negative numbers are **not** considered palindromes.

Examples

Input: x = 121

Output: true

Explanation: 121 reads the same forward and backward.

Input: x = -121

Output: false

Explanation: Reversed = 121-, which is not valid.

Input: x = 10

Output: false

Explanation: Reversed = 01, which is not equal to 10.

Approach

Approach: Reverse Integer Comparison

  • If `x` is negative, immediately return `false`.
  • Initialize a `reversed` variable to 0 and store the original value in a temporary variable `temp`.
  • While `temp > 0`:
  • - Extract the last digit: `lastDigit = temp % 10`
  • - Build reversed number: `reversed = reversed * 10 + lastDigit`
  • - Remove last digit: `temp = Math.floor(temp / 10)`
  • After the loop, compare `reversed` with `x`. If equal, return `true`; otherwise, return `false`.
// 🔹 Approach: Reversing Number
  var isPalindrome = function (x) {
    if (x < 0) return false;
  
    let temp = x;
    let reversed = 0;
  
    while (temp > 0) {
      let lastDigit = temp % 10;
      reversed = reversed * 10 + lastDigit;
      temp = Math.floor(temp / 10);
    }
  
    return reversed === x;
  };

Complexity

Time: O(log₁₀n) – We divide the number by 10 each iteration

Space: O(1) – Constant space for variables

Watch Explanation

📊 Presentation (PPT)

📥 Download PPT

📎 Resources