简体   繁体   中英

How to obtain the closest, lowest palindrome of a given number

I am trying to modify the answer to give me the closest lowest palindrome number.

I have tried modifying the answer to this:

     def lowest(n):
        s = str(n + 1)
        l = len(s)
        if s[:l//2][::-1] < s[(l+1)//2:]:
            head = str(int(s[:(l+1)//2]))
        else:
            head = s[:(l+1)//2]
        print int(head + head[:l//2][::-1])

But for the number 1000, it still returns 1001. What am i doing wrong?

In case you are looking for the previous palindrome, you have invert a couple of signals in the linked answer and add an edge-case exception (for 10^k+1, for all even k>0)

def prev_palindrome(n):
    s = str(n - 1)
    l = len(s)
    if s[:l//2][::-1] > s[(l+1)//2:]:
        head = str(int(s[:(l+1)//2])-1)
    else:
        head = s[:(l+1)//2]
    if len(head) < l/2:
        return int(head + '9' + head[:l//2][::-1]) #edge case
    else:
        return int(head + head[:l//2][::-1])

If you want the closest you can try:

nxt = next_palindrome(n)
prv = prev_palindrome(n)

if abs(prv-n) <= abs(nxt-n):
    print prv
else:
    print nxt

Please note that both next_palindrome and prev_palindrome returns are strictly higher/lower than n .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM