Palindrome Number

Updated Jun 16, 2024#leetcode#dsa

The Palindrome Number problem is a common coding challenge that often appears in technical interviews and programming competitions. The objective of this problem is to determine whether a given integer is a palindrome or not.

A palindrome is a number that reads the same forwards and backward. In other words, when its digits are reversed, the resulting number remains the same.

Using JavaScript

To solve this problem, one common approach is to convert the integer to a string and then check if the string is a palindrome by comparing characters from both ends.

function isPalindrome(x) {
  // Convert the number to a string
  const str = x.toString();

  // Use two pointers to check if the string is a palindrome
  let left = 0;
  let right = str.length - 1;

  while (left < right) {
    if (str[left] !== str[right]) {
      return false;
    }
    left++;
    right--;
  }

  return true;
}

It’s also possible to solve the problem without converting the integer to a string by reversing the integer and comparing it with the original value. The problem tests skills in handling integer manipulation, loops, and conditionals.

function isPalindrome(x) {
  // Check for negative numbers and multiples of 10
  if (x < 0 || (x !== 0 && x % 10 === 0)) {
    return false;
  }

  let reversed = 0;
  let original = x;

  while (x > 0) {
    const digit = x % 10;
    reversed = reversed * 10 + digit;
    x = Math.floor(x / 10);
  }

  return original === reversed;
}

console.log(isPalindrome(121)); // true
console.log(isPalindrome(-121)); // false
console.log(isPalindrome(10)); // false
console.log(isPalindrome(12321)); // true
console.log(isPalindrome(12345)); // false

Using Swift

func isPalindrome(_ x: Int) -> Bool {
    return String(x) == String(String(x).reversed())
}

or

func isPalindrome(_ x: Int) -> Bool {
    if x < 0 {
        return false
    }
    
    var num: Int = x
    var reversed: Int = 0
    
    while num != 0 {
        let digit = num % 10
        num = num / 10
        reversed = reversed * 10 + digit
    }
    
    return reversed == x
}