2. Add Two Numbers

时隔两个月又写了一次,写出来的code变化不大,除了会设置 dummy head 了...

看到另一个方法是利用加法累进,就是竖式加减的思路。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        def linkedListToNumber(head):
            number = 0
            digit = 1
            while head:
                number += digit * head.val
                digit *= 10
                head = head.next
            return number
        _sum = linkedListToNumber(l1) + linkedListToNumber(l2)
        res = ListNode(0)
        cur = res
        for i in str(_sum)[::-1]:
            cur.next = ListNode(int(i))
            cur = cur.next
        return res.next

Last updated

Was this helpful?