DEV Community

Cover image for Determine whether an integer is a palindrome
chandra penugonda
chandra penugonda

Posted on • Updated on

Determine whether an integer is a palindrome

Good morning! Here's your coding interview problem for today.

This problem was asked by Bloomberg.

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Follow up: Coud you solve it without converting the integer to a string?

Example

function isPalindrome(x) {

}

console.log(isPalindrome(121)) // true
console.log(isPalindrome(-121)) // false
console.log(isPalindrome(10)) // false
Enter fullscreen mode Exit fullscreen mode

Solution

function isPalindrome(x) {
  if (x < 0) return false;
  let num = x;
  let reversed = 0;
  while (num > 0) {
    reversed = reversed * 10 + (num % 10);
    num = Math.floor(num / 10);
  }
  return reversed === x;
}

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

Enter fullscreen mode Exit fullscreen mode

Explanation

  • Handle negative numbers by returning false early.
  • Initialize reversed to 0.
  • While the original number num is greater than 0:
  • Take the remainder of num divided by 10 to extract the last digit
  • Add that digit to the reversed number multiplied by 10
  • Remove the last digit from num by dividing by 10
  • Once the original num reaches 0, reversed will contain the digits in reverse order. Compare it to the original x to determine if it is a palindrome.
  • This iterates through the digits of x once while reconstructing the reverse order in reversed. It avoids converting the integer to a string.

Top comments (0)