Skip to content

Instantly share code, notes, and snippets.

@ranasaani
Created May 3, 2019 17:55
Show Gist options
  • Save ranasaani/e16a9a7e4e740c99a832c6431db21420 to your computer and use it in GitHub Desktop.
Save ranasaani/e16a9a7e4e740c99a832c6431db21420 to your computer and use it in GitHub Desktop.
Find the Closest Palindrome
def convert_palindrome(_str):
first_half = _str[:int(len(_str)/2)]
middle = _str[int(len(_str)/2)]
if middle == '0':
middle = '9'
first_half = str(int(first_half) -1 )
elif middle == '9':
middle = '0'
first_half = str(int(first_half) +1 )
second_half = ''
for s in first_half:
second_half = '{}{}'.format(s, second_half)
return '{}{}{}'.format(first_half, middle, second_half)
def find_palindrome(num):
int_to_str = ''
while num > 0:
int_to_str = '{}{}'.format(str(num % 10), int_to_str)
num = int(num/10)
return convert_palindrome(int_to_str)
find_palindrome(29024)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment