DEV Community

Cover image for Palindrome number - LeetCode
zuzexx
zuzexx

Posted on

Palindrome number - LeetCode

Given an integer x, return true if x is a
palindrome, and false otherwise.

In this challenge, we are tasked to determine if a given integer is a palindrome or not. A palindrome is a number that remains the same when its digits are reversed. For example, 121 is a palindrome, but 123 is not.

The solution to this challenge is to convert the integer into a string, reverse the string, and compare it to the original string. If the two strings are equal, then the number is a palindrome.

var isPalindrome = function(x) {
    let stringified = x.toString();
  let reverse = stringified.split('').reverse().join('');
  return stringified === reverse;
};
Enter fullscreen mode Exit fullscreen mode

The function isPalindrome takes in a single integer as an argument and returns a boolean value indicating whether or not it is a palindrome. The first step is to convert the integer into a string using toString().

Next, we use the split() method to convert the string into an array of characters. We then use the reverse() method to reverse the order of the characters in the array. Finally, we use the join() method to convert the array back into a string. This string represents the reverse of the original string.

Finally, we compare the original string and the reversed string using the equality operator (===). If the two strings are equal, then the function returns true, indicating that the number is a palindrome. If the two strings are not equal, then the function returns false, indicating that the number is not a palindrome.

Overall, this solution is straightforward and efficient, with a time complexity of O(n) and a space complexity of O(n), where n is the length of the string representation of the integer.

Top comments (0)