🔗LC9 🟢 Easy 🧩 Pattern – math logic
Given an integer x, return true if x is a PALINDROME, and false otherwise.
Follow up: Could you solve it without converting the integer to a string?
Example
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.Code language: JavaScript (javascript)Solution
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function (x) {
// Reject negative numbers numbers OR
// numbers ending with zero except zero
if (x < 0 || (x % 10 === 0 && x !== 0)) {
return false;
}
// We reverse only half the number and compare
let reversed = 0;
while (x > reversed) {
reversed = reversed * 10 + (x % 10);
x = Math.trunc(x / 10);
}
// For even length numbers: x === reversed
// For odd length numbers: x === Math.floor(reversed / 10)
// such as 787, 78 !== 7 so trunc(78/10) => 7 == 7
return x === reversed || x === Math.trunc(reversed / 10);
};Code language: JavaScript (javascript)