Closest palindrome number
Sample input
19
Sample output
22
Number = str(input())
L = len(Number)
if (L == 1):
print(Number)
else:
if (L % 2 == 0):
temp = int(Number[:L // 2]) # take the first half of the number, change it to +-1, build a palindrome and choose the closest one
a = str(temp) + str(temp)[::-1] # first palindrome
b = str(temp + 1) + str(temp + 1)[::-1] # second palindrome
c = str(temp - 1) + str(temp - 1)[::-1] # third palindrome
else:
temp = int(Number[:L // 2 + 1])
a = str(temp) + str(temp)[-2::-1] # first palindrome
b = str(temp + 1) + str(temp + 1)[-2::-1] # second palindrome
c = str(temp - 1) + str(temp - 1)[-2::-1] # third palindrome
a = int(a)
b = int(b)
c = int(c)
Number = int(Number)
if (abs(Number - a) <= abs(Number - b)) and (abs(Number - a) <= abs(Number - c)): # which one is closest
print(a)
elif (abs(Number - b) <= abs(Number - a)) and (abs(Number - b) <= abs(Number - c)):
print(b)
else:
print(c)
Comments
Leave a comment