题解 P1015 【回文数】
浏览了一圈没有看到使用 Python 的, 这儿用 python 有一个大坑,就是读入的数据有一个回车,如果没有处理的话就会全部 RE
还有一个坑是题目中要求的是 N 进制的回文串,所以判断回文串的时候不用将数字转换为十进
如下的代码,如果直接使用 int(ch,base=n) 而不处理异常的话就会全部 RE (0分)
n = int(input())
instr = input()
a = []
for ch in instr:
try:
a.append(int(ch,base=n))
except Exception:
# must handle exception !!!
pass
step = 0
while step <= 30:
b = a[::-1]
if a == b:
break
# add b and b.revert()
a = []
up = 0
for index in range(len(b)):
s = b[index] + b[-1 - index] + up
a.append(s % n)
up = 1 if s >= n else 0
if up == 1:
a.append(1)
step += 1
if step <= 30:
print("STEP="+str(step))
else:
print("Impossible!")