大数处理-大数相减问题 (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'
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值