Skip to content

Instantly share code, notes, and snippets.

@marcogbarcellos
Last active February 11, 2017 03:47
Show Gist options
  • Save marcogbarcellos/b5f9304e9152440907fb69b401f18fee to your computer and use it in GitHub Desktop.
Save marcogbarcellos/b5f9304e9152440907fb69b401f18fee to your computer and use it in GitHub Desktop.
Given a number, find the next palindrome on which this next palindrome is larger than the given number.
//We can check that the Recursive Version of Palindrome is way faster...
function palindromeRecursive(n) {
var nArr = n.split('');
if(nArr.length <= 1) {
return true;
}
else {
if(nArr[0] === nArr[nArr.length-1]){
return palindromeRecursive(n.slice(1, nArr.length-1));
} else {
return false;
}
}
}
function isPalindrome(word) {
var wordArray = word.split('');
var left = 0;
var right = wordArray.length-1;
while (left < right) {
if(wordArray[left] !== wordArray[right]) {
return false;
}
left++;
right--;
}
return true;
}
function nextPalLargerThanNumber (numberPal, callback) {
console.time('how long?');
var isPal = isPalindrome(numberPal.toString());
while(!isPal) {
numberPal++;
isPal = isPalindrome(numberPal.toString());
}
console.timeEnd('how long?');
console.log('next Palindrome:',numberPal);
callback(numberPal);
}
function nextPalLargerThanNumberRecursive (numberPal) {
console.time('how long RECURSIVE?');
var isPal = palindromeRecursive(numberPal.toString());
while(!isPal) {
numberPal++;
isPal = palindromeRecursive(numberPal.toString());
}
console.timeEnd('how long RECURSIVE?');
console.log('next Palindrome:',numberPal);
}
var numberPal = 4545485848550; //with this one, should return 4554
nextPalLargerThanNumber(numberPal,nextPalLargerThanNumberRecursive);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment