Topics
Math


Palindrome Number (opens in a new tab)

  • Build a number starting with the last digit of the input number using modulo and division
  • Compare the reversed number with the input number
/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function (x) {
  if (x < 0) {
    // if negative number
    return false;
  }
 
  let reverse = 0, value = x;
  while (value > 0) {
    const remainder = value % 10; // get the last digit
    reverse = remainder + reverse * 10; // build the reversed number
    value = Math.floor(value / 10); // remove the last digit
  }
 
  return reverse === x;
};
Complexity
  • Time: O(digits)
  • Space: O(1)


Reverse Integer (opens in a new tab)

  • Reverse the number without sign and check for overflow
  • Use the sign to return the reversed number with the correct sign
/**
 * @param {number} x
 * @return {number}
 */
var reverse = function (x) {
  const limit = Math.pow(2, 31);
  const isPositive = x > 0;
 
  let value = Math.abs(x); // remove the sign
  let reverse = 0;
  while (value > 0) {
    const remainder = value % 10;
    value = Math.floor(value / 10);
    reverse = remainder + 10 * reverse;
  }
 
  // check for overflow
  if (isPositive && reverse >= limit) {
    return 0;
  } else if (!isPositive && reverse > limit) {
    return 0;
  }
 
  // return the reversed number with the correct sign
  return isPositive ? reverse : -reverse;
};
Complexity
  • Time: O(digits)
  • Space: O(1)