Skip to content

Instantly share code, notes, and snippets.

@jessicatarra
Last active March 28, 2022 23:14
Show Gist options
  • Save jessicatarra/84d9da82f0fa16aec89b46e6b45c9887 to your computer and use it in GitHub Desktop.
Save jessicatarra/84d9da82f0fa16aec89b46e6b45c9887 to your computer and use it in GitHub Desktop.
Palindrome Number
// Example #1
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
if (x < 0) return false
let rev = 0
for(let i = x; i >= 1; i = Math.floor(i/10)) rev = rev*10 + i%10
return rev === x
};
// Example #2
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
if(x<0) return false;
return reverse(x)===x;
};
function reverse(num){
let out = 0, rem = 0;
while(num){
rem = num%10;
out = out*10 + rem;
num = Math.floor(num/10);
}
return out;
}
// Example #3 - String 🙅‍♀️
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
if (x < 0) return false;
// reverse the string representation of x
const reverse = `${x}`.split('').reverse().join('');
// compare the value regardless of types
return x == reverse;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment