注意、非回文数反转时,首数字有可能是0,输出字符串格式即可
注意、对字符串遍历时,可以不用考虑字符串长度时偶数还是奇数,用字符串长度除以2取整即可得到遍历查找对比的次数
注意、灵活使用for...else语句,区别break和exit()的区别
n = input()
for i in range(10):
l = len(n)
w = int(l/2)
for k in range(w):
if n[k] == n[l-1-k]:
pass
else:
break
else:
print("%s is a palindromic number." % n)
exit()
m = n[::-1]
s = int(n) + int(m)
print("%s + %s = %d" % (n,m,s))
n = str(s)
print("Not found in 10 iterations.")
判段字符串长度奇偶性,再遍历
n = input()
for i in range(10):
l = len(n)
if l % 2 == 0: # 判断字符串长度是奇数还是偶数,方便后续循环查找比较
w = int(l/2)
else:
w = int((l-1)/2)
for k in range(w):
if n[k] == n[l-1-k]:
pass
else:
break
else:
print("%s is a palindromic number." % n) # 找到了回文数,输出字符串并退出
exit()
m = n[::-1]
s = int(n) + int(m)
print("%s + %s = %d" % (n,m,s))
n = str(s)
print("Not found in 10 iterations.")