# 2. Add Two Numbers

{% embed url="<https://leetcode.com/problems/add-two-numbers/>" %}

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

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

{% tabs %}
{% tab title="Decode and Encode" %}

```python
# 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
```

{% endtab %}

{% tab title="加法累进" %}

```python
class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        sumval = 0
        root = curr = ListNode(0)
        while l1 or l2 or sumval:
            if l1: 
                sumval += l1.val
                l1 = l1.next
            if l2: 
                sumval += l2.val
                l2 = l2.next
            curr.next = ListNode(sumval % 10)
            curr = curr.next
            sumval //= 10
        return root.next
```

{% endtab %}
{% endtabs %}
