Created
May 3, 2019 17:55
-
-
Save ranasaani/e16a9a7e4e740c99a832c6431db21420 to your computer and use it in GitHub Desktop.
Find the Closest Palindrome
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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