两个纯数字字符串相加Python实现版

"""
两个字符串相加
模拟两个大整数相加,但是不能直接相加,采用每一位相加的方式
"""


def add_large_numbers(num1, num2):
    # 反转字符串,方便从低位开始相加
    num1 = num1[::-1]
    num2 = num2[::-1]

    # 初始化结果列表和进位
    result = []
    carry = 0

    # 逐位相加
    i, j = 0, 0
    while i < len(num1) or j < len(num2) or carry:
        digit1 = int(num1[i]) if i < len(num1) else 0
        digit2 = int(num2[j]) if j < len(num2) else 0
        total = digit1 + digit2 + carry
        carry = total // 10
        digit = total % 10
        result.append(str(digit))
        i += 1
        j += 1

        # 反转结果列表并拼接成字符串
    return ''.join(result[::-1])


if __name__ == '__main__':
    num1 = "123456789012345678901234567890"
    num2 = "987654321098765432109876543210"
    print(add_large_numbers(num1, num2))

  

 

借鉴自B站视频

posted @ 2024-04-11 09:19  宝山方圆  阅读(12)  评论(0编辑  收藏  举报