字符串大数 -减法

描述

以字符串的形式读入两个数字,编写一个函数计算它们的和,以字符串形式返回。

代码实现

  • 大小判断:a - b 与 b - a 的绝对值相等
  • 将大的数放前面,抽离出结果的符号
import  random
s, t = str(random.randint(1000, 9999)), str(random.randint(1000, 9999))
# 大数减法
def subtraction(s, t):
    op = ''
    if s < t:
        op = '-'
        s, t = t, s
    if len(s) > len(t): # 补齐位数,减少循环中的逻辑判断
        t = '0' * (len(s) - len(t)) + t
    arr1, arr2, arr = list(map(int, list(s))), list(map(int, list(t))), []
    for i in range(len(arr1)-1, -1, -1):
        if arr1[i] >= arr2[i]:    
            arr.append(arr1[i] - arr2[i])
        else:
            j = i - 1
            while arr1[j] == 0:
                arr1[j] = 9
                j -= 1
            arr1[j] -= 1
            arr.append(10 + arr1[i] - arr2[i])   
    arr = map(str, arr[::-1])
    return op + ''.join(arr)                

print(
     s , t, int(s) - int(t), subtraction(s, t)
)

你可能感兴趣的:(算法,python)