# Участник:Alex.Galtseva/findTheClosestPalindrome

Перейти к: навигация, поиск
```class Solution(object):

# Judge whether + 1 or - 1 changes in digits
def change_bit(self, n):
if (len(str(n + 1)) != len(str(n))):
return 1
elif ((len(str(n - 1)) != len(str(n))) or (n == 1)):
return -1
else:
return 0

def find_min(self, min_n, mid_n, max_n, n):
min_abs = abs(int(min_n) - int(n))
mid_abs = abs(int(mid_n) - int(n))
max_abs = abs(int(max_n) - int(n))
if (mid_abs <= max_abs):
if (min_abs <= mid_abs):
return min_n
else:
return mid_n
else:
if (min_abs <= max_abs):
return min_n
else:
return max_n

def nearestPalindromic(self, n):
if (len(n) < 2):
return str(int(n) - 1)
if ((len(n) % 2) == 0):
substr_front = n[0:len(n) // 2]
mid_n = substr_front + substr_front[::-1]
maxsub_front = str(int(substr_front) + 1)
max_n = maxsub_front + maxsub_front[::-1]
minsub_front = str(int(substr_front) - 1)
min_n = minsub_front + minsub_front[::-1]
else:
substr_front = n[0:(len(n) + 1) // 2]
mid_n = substr_front + (substr_front[::-1])[1:len(substr_front)]
maxsub_front = str(int(substr_front) + 1)
max_n = maxsub_front + (maxsub_front[::-1])[1:len(maxsub_front)]
minsub_front = str(int(substr_front) - 1)
min_n = minsub_front + minsub_front[::-1][1:len(minsub_front)]
if (mid_n == n):
mid_n = "0"
if (self.change_bit(int(substr_front)) == 1):
max_n = '1' + ((len(n) - 1) * '0') + '1'
if (self.change_bit(int(substr_front)) == -1):
min_n = (len(n) - 1) * '9'

return self.find_min(min_n, mid_n, max_n, n)```