Closest palindrome Number:
Given a string N, representing an integer, return the closest integer(not including itself), which is palindrome. If there is a tie, return the smaller one. The closest is defined as the absolute difference minimized between two integers.
Input:
The input will be a single line containing an integer.
Output:
The output should be a single line containing a closest palindrome number to the given integer.
Explanation:
For example, if the given integer is 19, the palindrome number greater than 19 is 22 and the palindrome number less than 19 is 11. As 22 is closest to the number 19. So the output should be 22.
# closest Palindrome number
# Function to check Palindrome
def isPalindrome(n):
for i in range(len(n) // 2):
if (n[i] != n[-1 - i]):
return False
return True
# Convert number into String
def convertNumIntoString(num):
Snum = str(num)
return Snum
# Function return closest Palindrome number
def closestPalindrome(num):
# Case1 : largest palindrome number
# which is smaller than given number
RPNum = num - 1
while (not isPalindrome(
convertNumIntoString(abs(RPNum)))):
RPNum -= 1
# Case2 : smallest palindrome number
# which is greater than given number
SPNum = num + 1
while (not isPalindrome(
convertNumIntoString(SPNum))):
SPNum += 1
# Check absolute difference
if (abs(num - RPNum) > abs(num - SPNum)):
return SPNum
else:
return RPNum
# Driver Code
if __name__ == '__main__':
num = int(input())
print(closestPalindrome(num))
Comments
Leave a comment