大数处理-大数相减问题 (python 编程实现)

问题描述

两个长度超出常规整形变量上限的大数相减,避免使用各语言内置库。
输入
两个代表整数的字符串 a 和 b,长度超过百位。规定 a>=b,a, b > 0。
输出
返回表示结果整数的字符串。

实现思路

我的做法比较简单,可能不是最优方案。
就是按照我们手写除法时的方法,两个数字末位对齐,从后开始,按位相减,不够减时向前位借一。
最终结果需要去除首端的0.如果所有位都是0,则返回0。

编程实现(Python 3)

def solution(line):
    a,b = line.strip().split()
    a = [int(item) for item in a]
    b = [int(item) for item in b]
    res = ''
    for i in range(len(b)):
        flag_a = len(a)-1-i
        flag_b = len(b)-1-i
        if a[flag_a]>= b[flag_b]:
            res = str(a[flag_a]-b[flag_b])+res
        else:
            res = str(10+a[flag_a]-b[flag_b])+res
            while a[flag_a-1]==0:
                a[flag_a-1]=9
                flag_a -= 1
            a[flag_a-1] -= 1
    for j in range(len(a)-1-i-1,-1,-1):
        res = str(a[j])+res
    zero_flag=0
    for i in range(len(res)):
        if res[i]!='0':
            zero_flag=1
            break
    if zero_flag==0:
        return 0
    return res[i:]

测试

输入:

'312321321321321356577869973523323757753625424324324234 6456456754967595476'

输出:

'312321321321321356577869973523323751297168669356728758'

你可能感兴趣的:(编程思想,python,算法基础,python)