Palindrome Number LeetCode Cheat Sheet Javascript Solution
--
This LeetCode Challenge is really similar to the “reverse integer challenge” with a little spin. This time we want to return a boolean value.
The Palindrome challenge is in the easy category and is a good start for understanding more challenging algorithms. I will focus on explaining a solution that works and not on the O time and space complexity.
Palindrome Number Challenge
“Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.” (LeetCode)
Examplex= 565return truex= -565became 565- therefore not a palindrome
1.Let create a reversed version of x
const reversed = (x+””).split(‘’).reverse().join(‘’);
a)Convert the number into a string ex 565 became “565”
(x+””)
b)Split the string ex “565” became “5”,”6",”5"
.split(‘’)
c)Reverse the split string ex “5”,”6",”5" became “5”,”6",”5"
.reverse()
d)Join method will create a string by concatenating the elements of the array ex “5”,”6",”5" became “565”
.join(‘’)
2.compare is x.toString is strictly equal to its reversed version.
When using a comparison sign the result would be a boolean value, true or false.
return (x.toString() === reversed)
In our case, it will return true
Solution
var isPalindrome = function(x) {const reversed = (x+””).split(‘’).reverse().join(‘’);return (x.toString() === reversed);};