首页 > 超长正整数相加

超长正整数相加

# 请设计一个算法完成两个超长正整数的加法。
# 输入参数:
# str1:加数
# str2:被加数
# 返回值:加法结果

def AddLongInteger(str1, str2):
    str1 = str1[::-1]
    str2 = str2[::-1]
    if len(str1) > len(str2):
        str1, str2 = str2, str1
    sum_all = {}
    add_in = index = 0
    for index, val in enumerate(str2):
        if index >= len(str1):
            sum = int(val) + add_in
        else:
            sum = int(val) + int(str1[index]) + add_in
        add_in = 1 if sum > 9 else 0
        sum_all[index] = sum%10
    # 最后进位
    if add_in == 1:
        sum_all[index+1] = 1
    ret = ''
    for i in range(len(sum_all)):
        ret += str(sum_all[i])
    return ret[::-1]

print AddLongInteger("99999999999999999999999999999999999999999999999999", "1")

一直未通过,帮忙看看有什么问题?


简单改了下,试试这个。

pythondef AddLongInteger(str1, str2):
    str1 = str1.lstrip('+0')[::-1]
    str2 = str2.lstrip('+0')[::-1]
    if len(str1) > len(str2):
        str1, str2 = str2, str1
    sum_all = []
    add_in = index = 0
    for index, val in enumerate(str2):
        if index >= len(str1):
            sum = int(val) + add_in
        else:
            sum = int(val) + int(str1[index]) + add_in
        add_in = 1 if sum > 9 else 0
        sum_all.append(str(sum%10))
    if add_in == 1:
        sum_all.append('1')
    return ''.join(sum_all[::-1])

print AddLongInteger("+000099999999999", "+0001")

【热门文章】
【热门文章】