DEV Community

Masaki Fukunishi
Masaki Fukunishi

Posted on • Updated on

LeetCode #9 Palindrome Number with JavaScript

Solutions to LeetCode's 9. Palindrome Number with JavaScript.

Solution 3 addresses the following follow-up.
Follow up: Could you solve it without converting the integer to a string?

Solution 1: Converting the int to a string

/**
 * @param {number} x
 * @return {boolean}
 */
const isPalindrome = (x) => {
  const stringX = String(x);
  let reversed = "";
  for (let i = stringX.length - 1; i >= 0; i--) {
    reversed += stringX[i];
  }
  return reversed === stringX;
};
Enter fullscreen mode Exit fullscreen mode
  • Time complexity: O(n)
  • Space complexity: O(n)

Solution 2: Converting the int to a string (Recursion)

/**
 * @param {number} x
 * @return {boolean}
 */
const isPalindrome = (x) => {
  const stringX = String(x)
  if (stringX.length === 0 || stringX.length === 1) return true;
  if (stringX[0] === stringX[stringX.length - 1]) {
    return isPalindrome(stringX.slice(1, stringX.length - 1));
  } else {
    return false;
  }
};
Enter fullscreen mode Exit fullscreen mode
  • Time complexity: O(n)
  • Space complexity: O(n)

Solution 3: Without converting the int to a string

/**
 * @param {number} x
 * @return {boolean}
 */
const isPalindrome = (x) => {
  if (x < 0) return false;
  let number = x;
  let reversed = 0;
  while (number > 0) {
    reversed = (reversed * 10) + (number % 10);
    number = parseInt(number / 10);
  }
  return x === reversed;
};
Enter fullscreen mode Exit fullscreen mode
  • Time complexity: O(log10(n))
  • Space complexity: O(1)

Reverse one letter at a time, using the remainder divided by 10, leaving the number as it is.

Top comments (0)