Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active January 18, 2017 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save primaryobjects/e2807b3b64563c0a607c95270ca6a1a7 to your computer and use it in GitHub Desktop.
Save primaryobjects/e2807b3b64563c0a607c95270ca6a1a7 to your computer and use it in GitHub Desktop.
Checking if a number is a palindrome, without converting to a string. Demo at http://jsbin.com/panukukeda/edit?js,console
function getNthDigit(val, n)
{
var modVal = val % Math.pow(10,n);//Remove all digits larger than nth
return Math.floor(modVal / Math.pow(10,n-1));//Remove all digits less than nth
}
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
var result = true;
var length = Math.log(x) * Math.LOG10E + 1 | 0;
if (x < 0) {
result = false;
}
else if (length === 2 && x !== 11) {
result = false;
}
else {
for (var i=0; i<Math.ceil(length / 2); i++) {
var d1 = getNthDigit(x, i + 1);
var d2 = getNthDigit(x, length - i);
if (d1 != d2) {
result = false;
break;
}
}
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment