Search code examples
javascriptfunctionfor-looppalindrome

find the next palindrome using loop


i want to find next smallest palindrome but im not allowed to use some built-in function. so i create this code :

function reverse(nums) {
  var reverse = "";
  for (var i = String(nums).length - 1; i >= 0; i--) {
    reverse += String(nums)[i];
  }
  return reverse;
}

function Palindrome(num) {
  if (String(num).length < 2) {
    return num + 1
  }

  for (var i = num + 1; i < num + 3; i++) {
    if (String(i) === reverse(num)) {
      return i
    }
  }
}

console.log(Palindrome(23)) // 32

first function will reverse the string and the second will find the nearest palindrome. on the test case, the result are supposed to be 33.

but when i run the code the result is :

console.log(Palindrome(23))// 32

it only reversing the numbers. could you help me to find what could be wrong from my code?

thanks before.


Solution

  • correct code is:

    function reverse(nums) {
      var reverse = "";
      for (var i = String(nums).length - 1; i >= 0; i--) {
        reverse += String(nums)[i];
      }
      return reverse;
    }
    
    function Palindrome(num) {
      if (String(num).length < 2 && num < 9) {
        return num + 1
      }
    
      for (var i = num + 1; ; i++) {
        if (String(i) === reverse(i)) {
          return i
        }
      }
    }
    
    console.log(Palindrome(5));
    console.log(Palindrome(8));
    console.log(Palindrome(9));
    console.log(Palindrome(23));

    you were doing reverse of num in place of i