Nearest palindrome of a number in python

In this tutorial, we will see how to generate the nearest palindrome of a given number in Python if the given number is not a palindrome. By the end of this tutorial, you will be able to find the nearest palindrome with very simple and easy code. So, let’s begin the tutorial.

Nearest Palindrome in Python

A palindrome may be a string or a number that reads the same from both ends, i.e. if we reverse a word, it should be the same as the original word. Some of the examples of palindromes are madam, 101, etc.

In python, we check whether the given number or string is a palindrome by using the slicing operator. For generating the nearest palindrome of a number also we will be using the slicing operator. The nearest palindrome of a given number is obtained by adding 1 to the number until it is a palindrome. This is done by using a while loop recursively. When the condition is met, the number is given as output. The working code for the above is given as:

def palin(n):
    while(1):
        if n==int(str(n)[::-1]):
            return n
        n+=1
n=int(input())
print(palin(n))
     

Here first, we typecast the integer to string because we cannot use the slice operator on an integer. Then we typecast the string to an integer because we have to iterate the loop further by adding 1 if it is not a palindrome.

OUTPUT:
Suppose we give the input as 1456, the output will be
1551
Suppose we give the input as 2766236, the output will be
2766672

You can demonstrate the code by taking various numbers as input

Leave a Reply

Your email address will not be published.