
Write a function isPalindrome(x) that takes an integer x and returns true if it reads the same backward and forward; otherwise, returns false.
-121 ≠ 121-).| Metric | Complexity |
|---|---|
| Time Complexity | O(d) — where d is the number of digits |
| Space Complexity | O(1) — uses constant space |
| Input | Output | Explanation |
|---|---|---|
121 | true | Reads the same backward and forward |
-121 | false | Negative sign makes it non-palindromic |
10 | false | Reverse is 01 which ≠ 10 |
x < 0, return false.xCopy = x.rev = 0x > 0:
rem = x % 10rev = rev * 10 + remx = Math.floor(x / 10)rev === xCopy, return truefalsex = 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

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

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