{"id":26764,"date":"2022-04-18T01:27:31","date_gmt":"2022-04-17T19:57:31","guid":{"rendered":"https:\/\/python-programs.com\/?p=26764"},"modified":"2022-04-18T01:27:31","modified_gmt":"2022-04-17T19:57:31","slug":"python-program-to-find-nearest-palindrome-of-a-number","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-program-to-find-nearest-palindrome-of-a-number\/","title":{"rendered":"Python Program to Find Nearest Palindrome of a Number"},"content":{"rendered":"

Palindrome:<\/strong><\/p>\n

If a number reads the same both forward and backward, it is called a Palindrome number. And the insane part is that it doesn\u2019t just apply to numbers. Even if a string reads the same in both directions, it is always a Palindrome!<\/p>\n

For Example –\u00a0 <\/strong>121, 131, etc<\/p>\n

when we reverse 121 we get the same 121. Hence it is a Palindrome number.<\/p>\n

In this article, let us look at how to use Python to find the nearest palindrome to a given number if the provided number isn’t a palindrome.<\/p>\n

Examples:<\/strong><\/p>\n

Example1:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given Number = 620<\/pre>\n

Output:<\/strong><\/p>\n

The Nearest palindrome of the given number{ 620 } is:\r\n626<\/pre>\n

Example2:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given Number = 120<\/pre>\n

Output:<\/strong><\/p>\n

The Nearest palindrome of the given number{ 120 } is:\r\n121<\/pre>\n

Program to Find Nearest Palindrome of a Number in Python<\/h2>\n

Using the slicing operator in Python, we can determine whether a given number or string is a palindrome. We will also use the slicing operator to get the nearest palindrome of an integer. A given number’s nearest palindrome is found by adding 1 to the number until it is a palindrome. This is accomplished by recursively using a while loop. When the condition is satisfied, the number is output.<\/p>\n

Method #1: Using Slicing (Static Input)<\/h3>\n

Approach:<\/strong><\/p>\n