2.两数相加

2020-05-03  本文已影响0人  御坂10241
chaoxi_todo.jpg

题目

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

题解

思路:carry记录进位信息

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        res = ListNode(0)
        move = res
        carry = 0
        while l1 != None or  l2 != None:
            if l1 == None:
                l1, l2 = l2, l1
            if l2 != None:
                carry, l1.val = divmod((l1.val+l2.val+carry), 10)
                move.next = l1
                l1, l2, move = l1.next, l2.next, move.next
            else:
                carry, l1.val = divmod((l1.val+carry), 10)
                move.next =  l1
                l1, move = l1.next, move.next
        if carry != 0:
            move.next = ListNode(carry)
        return res.next

执行结果:通过
显示详情
执行用时 :56 ms, 在所有 Python3 提交中击败了99.36%的用户
内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.13%的用户

通过递归实现:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        def recursive(l1, l2, carry=0):
            if l1 == None and l2 == None:
                return ListNode(carry) if carry != 0 else None
            if l1 == None:
                l1, l2 = l2, l1
                return recursive(l1, None, carry)
            if l2 == None:
                carry, l1.val = divmod((l1.val+carry), 10)
                l1.next = recursive(l1.next, None, carry)
                return l1
            carry, l1.val = divmod((l1.val+l2.val+carry), 10)
            l1.next = recursive(l1.next, l2.next, carry)
            return l1
        return recursive(l1, l2)
上一篇 下一篇

猜你喜欢

热点阅读