num1 = input()
num2 = input()
def compare(num1,num2):
for i in range(len(num1)):
if num1[i]>num2[i]:
return 0
elif num1[i]<num2[i]:
return 1
return 2
# 解析符号
flag1 = 0
flag2 = 0
if num1[0] == "-":
flag1 = 1
num1 = num1[1:]
if num2[0] == "-":
flag2 = 1
num2 = num2[1:]
# 对齐数位
num1_len = len(num1)
num2_len = len(num2)
if num1_len < num2_len:
for _ in range(num2_len - num1_len):
num1 ="0" + num1
else:
for _ in range(num1_len - num2_len):
num2 ="0" + num2
# 制作返回数组
num1_arr = [int(c) for c in num1]
num2_arr = [int(c) for c in num2]
length = len(num1)
if flag1 == 0 and flag2 == 0:
res = [0]*(length+1)
temp = 0
for i in range(length-1,-1,-1):
if num1_arr[i]+num2_arr[i]+temp >= 10:
res[i+1] = num1_arr[i]+num2_arr[i]+temp -10
temp = 1
else:
res[i+1] = num1_arr[i]+num2_arr[i]+temp
temp = 0
if temp == 1:
res[0] = 1
if res[0] == 1:
print("".join(str(c) for c in res))
else:
print("".join(str(c) for c in res[1:]))
if flag1 == 1 and flag2 == 1:
res = [0]*(length+1)
temp = 0
for i in range(length-1,-1,-1):
if num1_arr[i]+num2_arr[i]+temp >= 10:
res[i+1] = num1_arr[i]+num2_arr[i]+temp -10
temp = 1
else:
res[i+1] = num1_arr[i]+num2_arr[i]+temp
temp = 0
if temp == 1:
res[0] = 1
if res[0] == 1:
print("-"+"".join(str(c) for c in res))
else:
print("-"+"".join(str(c) for c in res[1:]))
if flag1 == 1 and flag2 == 0:
res = [0]*length
if compare(num1_arr,num2_arr) == 0:
for i in range(length-1,-1,-1):
if num1_arr[i]>=num2_arr[i]:
res[i] = num1_arr[i] - num2_arr[i]
else:
num1_arr[i-1] -= 1
res[i] = num1_arr[i]+10 - num2_arr[i]
for i in range(len(res)):
if res[i] != 0:
print("-"+"".join(str(c) for c in res[i:]))
break
elif compare(num1_arr,num2_arr) == 1:
for i in range(length-1,-1,-1):
if num2_arr[i]>=num1_arr[i]:
res[i] = num2_arr[i] - num1_arr[i]
else:
num2_arr[i-1] -= 1
res[i] = num2_arr[i]+10 - num1_arr[i]
for i in range(len(res)):
if res[i] != 0:
print("".join(str(c) for c in res[i:]))
break
elif compare(num1_arr,num2_arr) == 2:
print("0")
if flag1 == 0 and flag2 == 1:
res = [0]*length
if compare(num1_arr,num2_arr) == 0:
for i in range(length-1,-1,-1):
if num1_arr[i]>=num2_arr[i]:
res[i] = num1_arr[i] - num2_arr[i]
else:
num1_arr[i-1] -= 1
res[i] = num1_arr[i]+10 - num2_arr[i]
for i in range(len(res)):
if res[i] != 0:
print("".join(str(c) for c in res[i:]))
break
elif compare(num1_arr,num2_arr) == 1:
for i in range(length-1,-1,-1):
if num2_arr[i]>=num1_arr[i]:
res[i] = num2_arr[i] - num1_arr[i]
else:
num2_arr[i-1] -= 1
res[i] = num2_arr[i]+10 - num1_arr[i]
for i in range(len(res)):
if res[i] != 0:
print("-"+"".join(str(c) for c in res[i:]))
break
elif compare(num1_arr,num2_arr) == 2:
print("0")
标签:arr,num1,num2,大数,Python,res,temp,加法,print
From: https://www.cnblogs.com/DCFV/p/18390034