Last active
January 18, 2017 21:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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