## 题目描述：

LeetCode 564. Find the Closest Palindrome

Given an integer n, find the closest integer (not including itself), which is a palindrome.

The 'closest' is defined as absolute difference minimized between two integers.

Example 1:

```Input: "123"
Output: "121"
```

Note:

1. The input n is a positive integer represented by string, whose length will not exceed 18.
2. If there is a tie, return the smaller one as answer.

## 题目大意：

1. n是字符串表示的正整数，长度不超过18。
2. 如果距离相等，返回值较小的整数。

## Python代码：

``````class Solution(object):
def nearestPalindromic(self, n):
"""
:type n: str
:rtype: str
"""
evenPal = lambda sp : int(sp + sp[::-1])
oddPal = lambda sp : int(sp + sp[::-1][1:])
sn, n = n, int(n)
if len(sn) == 1: return str(n - 1)
ans = -999999999999999999
mid = len(sn) / 2
for sp in sn[:mid], sn[:mid + 1], str(int(sn[:mid]) * 10):
p = int(sp)
for pal in evenPal, oddPal:
for d in -1, 0, 1:
val = pal(str(p + d))
if val == n: continue
ans = min(ans, val, key = lambda x : (abs(x - n), x))
return str(ans)
``````

Pingbacks已关闭。