9. Palindrome Number

Solution (toString)

/**
 * @param {number} x
 * @return {boolean}
 */
 var isPalindrome = function(x) {
    const n = Number(x.toString().split('').reverse().join(''));
    return n === x;
};

Solution (reverse number)

/**
 * @param {number} x
 * @return {boolean}
 */
 var isPalindrome = function(x) {
    let original = x;
    let reversed = 0;
    
    for (let i = 1; x > 0; i *= 10) {
        const a = x % 10;
        x = x / 10 | 0;
        reversed *= 10;
        reversed += a;
    }

    return original === reversed;
};

Complexity

  • Time Complexity: O(N), where N is the number of characters in of x.
  • Space Complexity: O(1).

All Solutions