Description
Input
输入首先在第一行给出一个 N 位的进制表(0 < N ≤ 20),以回车结束。 随后两行,每行给出一个不超过 N 位的非负的 PAT 数。
Output
在一行中输出两个 PAT 数之和。
Sample Input
30527
06203
415
Sample Output
7201
参考程序
def Normal(st1,st2):
if len(st1)<len(st2):
st1="0"*(len(st2)-len(st1))+st1
else:
st2="0"*(len(st1)-len(st2))+st2
return st1+" "+st2
table=input()
num1=input()
num2=input()
num1,num2=Normal(num1,num2).split(" ")
c=0
res=[]
for i in range(-1,-len(num1)-1,-1):
mod=int(table[-1])
try:
tempsum=(int(num1[i])+int(num2[i])+c)%mod
except:
mod=10
tempsum=(int(num1[i])+int(num2[i])+c)%mod
res.append(tempsum)
c=(int(num1[i])+int(num2[i])+c)//mod
table=table[:len(table)-1]
while c!=0:
if len(table)==0:
res.append(c%10)
c=c//10
else:
mod=int(table[-1])
try:
tempsum=c%mod
except:
tempsum=c%10
res.append(tempsum)
c=c//mod
table=table[:len(table)-1]
ans=""
for i in range(-1,-len(res)-1,-1):
ans+=str(res[i])
ans=ans.lstrip("0")
if len(ans)==0:
print(0)
else:
print(ans)
分析:
本题主要算法思想是“大整数加法”,基本步骤是,首先将两个数对阶,即保证两个数据一样长(上述程序的Normal函数),然后从字符串的最后一位(下标为-1)开始,逐步向前推进,各位相加再加上进位c(初始进位为0)根据进制表取余,商作为下一位计算的进位。注意运算是需要将字符型数据转换为整型。
容易忽略的几个地方是,①每一位都加完了,最后一步仍有进位产生,这时如果进制表不够用,那么默认是按十进制转换c,否则按照进制表转换即可。
②res列表存储一位一位分开的结果,需要逆置再串联起来形成字符串。但此时字符串的前面很多o,需要忽略若干前导0,使用lstrip(“0”)方法,即去掉字符串左边的所有0.
③如果去除完毕,字符串为空,此时要输出一个0.
下面举几个例子
例1
输入:
1234
00
00
输出:
0
例2
输入:
2222
6203
9415
输出:
91010
例3
输入:
30527
29416
00001
输出:
100000
本题是PAT (Basic Level)1074 题,算法思路并不难,但是要仔细审题,考虑全面,拿满分还是不太容易的,本人做这道题的时候也是被困扰了很久,学习了其他大佬的经验分享才通过。欢迎各位批评指正!