Finding the Next Palindrome Number - Codewars Solution in JavaScript


 Finding the Next Palindrome Number


Given a positive integer val, the goal is to create a function nextPal() that will output the smallest palindrome number higher than val. A palindrome number is a number that is the same when written forwards or backwards, such as 121 or 1331.

One possible approach to solve this problem is to increment val by 1 and then check if the resulting number is a palindrome. If it is, we can return that number as the result. If it is not, we can repeat the process until we find the next palindrome number.


Here is an implementation of this solution in JavaScript:


Here is an example of how the nextPal function could be used:


In the example above, the val is 123. The nextPal function is called with val as the argument, and the resulting next palindrome number is printed to the console. In this case, 131 is the next palindrome number higher than 123, so the output is 131.


This solution has a time complexity of O(n^2), where n is the number of digits in the input number, because we increment the input number by 1 and then check if it is a palindrome. The space complexity is O(n), because we store the input number as a string of length n.


In conclusion, this solution incrementally checks if the numbers higher than val are palindromes and returns the first one that is. This solution has a time complexity of O(n^2) and a space complexity of O(n).


Please  follow and share this series on your story so that it can be beneficial for others as well.


Follow @devtipsdaily for more!

Post a Comment

Previous Post Next Post