Back to Interview Prep

Warm Up · Palindrome

Check if a Number is a Palindrome

Problem Statement

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

Requirements

  • Handles both positive and negative integers.
  • Return false for negative numbers (they are not palindromes).

Examples

Input: 121→Output: true

Input: -121→Output: false

Input: 10→Output: false

Approach

  • Handle Negatives: If x < 0, return false.
  • Store Original: Save the input in xCopy for comparison.
  • Reverse: Initialize rev = 0. While x > 0: rem = x % 10, rev = rev * 10 + rem, x //= 10.
  • Compare: If rev === xCopy return true, else false.

Time & Space Complexity

Time Complexity: O(d) - where d is the number of digits.

Space Complexity: O(1) - only a few variables are used.

Visualisation

1Read the numberx = 121
2Keep a copy and start reversed at 0xCopy = 121, rev = 0
3Build the reverse digit by digitrev = rev * 10 + x % 10
4Comparerev === xCopy → palindrome

Your solution

Solve it in JavaScript and print the answer with console.log(). Run to see your output, then Submit to check it against the test cases.

// Write your solution in JavaScript
// Print the answer with console.log()


Console

No output yet. Use console.log() to print values here.

Write your own solution and press Submit once to unlock the answer.

You're viewing a free lesson. Sign up free to track your progress and unlock the full course.Sign up freeSign in