Created
August 17, 2014 06:47
-
-
Save iambibhas/d7737463b5d33402c11d to your computer and use it in GitHub Desktop.
Find the palindrome larger than given number
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
import math | |
def find_next(n): | |
try: | |
n = int(n) | |
except: | |
return n | |
if n < 10: | |
return n | |
n += 1 | |
length = len(str(n)) | |
for i in range(1, ((length)/2)+1): | |
# extract first and last i digits of n | |
fd = str(n)[0:i] | |
ld = str(n)[-i:][::-1] | |
# increase n by 10^i-1(1, 10, 100 ...) in each loop | |
# and check if first and last i digits are equal | |
# if n = 2133, first increate by 1 until last digit is 2 | |
# then increate by 10 untill first 2 and last 2 digits are equal | |
while fd != ld: | |
n += int(math.pow(10, i-1)) | |
fd = str(n)[0:i] | |
ld = str(n)[-i:][::-1] | |
return n | |
print find_next(1111111112) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment