python 算法 两数相加多种解法
  2w4aEVgWpeJp 2023年12月08日 19 0

在 Python 中,有多种解法可以实现两数相加。以下是几种常见的解法:

  1. 逐位相加:将两个数的每一位进行相加,并考虑进位。使用循环遍历两个数的每一位,将对应位相加并考虑进位,然后将结果添加到一个新的列表中。最后,将列表转换为整数即可得到最终结果。
def addTwoNumbers(l1, l2):
    carry = 0
    head = ListNode(0)
    curr = head

    while l1 or l2:
        x = l1.val if l1 else 0
        y = l2.val if l2 else 0
        sum = carry + x + y
        carry = sum // 10
        curr.next = ListNode(sum % 10)
        curr = curr.next

        if l1: l1 = l1.next
        if l2: l2 = l2.next

    if carry > 0:
        curr.next = ListNode(carry)

    return head.next
  1. 递归相加:可以使用递归的方式实现两数相加。递归地处理每一位的相加,并将进位传递到下一位的相加中。
def addTwoNumbers(l1, l2, carry=0):
    if not l1 and not l2 and not carry:
        return None
    x = l1.val if l1 else 0
    y = l2.val if l2 else 0
    sum = carry + x + y
    carry = sum // 10
    result = ListNode(sum % 10)
    l1_next = l1.next if l1 else None
    l2_next = l2.next if l2 else None
    result.next = addTwoNumbers(l1_next, l2_next, carry)
    return result
  1. 倒序相加:如果两个数的位数不一致,可以在相加之前先将两个数补齐为相同长度。然后从最低位开始逐位相加,并考虑进位。
def addTwoNumbers(l1, l2):
    len1 = get_length(l1)
    len2 = get_length(l2)

    if len1 > len2:
        l2 = pad_zeros(l2, len1 - len2)
    else:
        l1 = pad_zeros(l1, len2 - len1)

    head = ListNode(0)
    curr = head
    carry = 0

    while l1 and l2:
        sum = l1.val + l2.val + carry
        carry = sum // 10
        curr.next = ListNode(sum % 10)
        curr = curr.next
        l1 = l1.next
        l2 = l2.next

    if carry > 0:
        curr.next = ListNode(carry)

    return head.next

def get_length(node):
    length = 0
    while node:
        length += 1
        node = node.next
    return length

def pad_zeros(node, num_zeros):
    for _ in range(num_zeros):
        new_node = ListNode(0)
        new_node.next = node
        node = new_node
    return node

这些都是两数相加的常见解法,在实际应用中可以根据具体需求选择合适的方法。

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月08日 0

暂无评论

推荐阅读
  2Fnpj8K6xSCR   2024年05月17日   80   0   0 Python
  xKQN3Agd2ZMK   2024年05月17日   65   0   0 Python
  fwjWaDlWXE4h   2024年05月17日   31   0   0 Python
2w4aEVgWpeJp