def dig(l, n, pos):
"""pos: 1 to n; left to right"""
pos = l - pos + 1
k = 10 ** pos
r = n % k
return r / (k / 10)
def inc_dig(l, n, val, pos):
"""pos: 1 to n; left to right"""
pos = l - pos + 1
if pos == 1:
return n + 1
return n + (val * (10 ** (pos-1)))
def replace_dig(l, n, posi, posj):
"""pos: 1 to n; left to right"""
d1 = dig(l, n, posi)
d2 = dig(l, n, posj)
sub = (d2 - d1) * (10 ** (l - posj))
n -= sub
return n
def palin(n):
l = len(str(n))
if l % 2 == 0:
k = l / 2
else:
k = (l - 1) / 2
i = 1
while i <= k:
if str(n) == str(n)[::-1]:
return n
if dig(l, n, i) < dig(l, n, l-i+1):
n = inc_dig(l, n, 1, l-i)
n = replace_dig(l, n, i, l-i+1)
if dig(l, n, l-i) == 0:
i -= 1
continue
i += 1
return n
t = int(raw_input())
for i in range(t):
print palin(int(raw_input()) + 1)
I am new to algos and spoj and above is my code.
I actually tried to operate on strings first.. My code was successful but exceeded the time limit. This time, I thought to play with numbers directly..
This code is unfortunately raising NZEC.. strange..
Can anyone help me find why exactly its raising.
Thanks