DEV Community

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

Posted on • Edited 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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay