Answer to Question #310279 in Python for ClosestPalindrome

Question #310279

Closest palindrome number



Sample input


19


Sample output


22

1
Expert's answer
2022-03-12T12:46:03-0500
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)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS