Skip to content

Instantly share code, notes, and snippets.

@iambibhas
Created August 17, 2014 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iambibhas/d7737463b5d33402c11d to your computer and use it in GitHub Desktop.
Save iambibhas/d7737463b5d33402c11d to your computer and use it in GitHub Desktop.
Find the palindrome larger than given number
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