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
falsefor 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
xCopyfor comparison. - Reverse: Initialize
rev = 0. Whilex > 0:rem = x % 10,rev = rev * 10 + rem,x //= 10. - Compare: If
rev === xCopyreturntrue, elsefalse.
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 number
x = 1212Keep a copy and start reversed at 0
xCopy = 121, rev = 03Build the reverse digit by digit
rev = rev * 10 + x % 104Compare
rev === xCopy → palindromeYour 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.