---
# System prepended metadata

title: 2. Add Two Numbers
tags: [Leetcode, list, medium, python, Top 100 Liked Questions]

---

###### tags: `Leetcode` `medium` `list` `python` `Top 100 Liked Questions`

# 2. Add Two Numbers

## [題目來源:] https://leetcode.com/problems/add-two-numbers/

## 題目:
You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

![](https://i.imgur.com/xYrG04I.png)

**Example 2:**
```
Input: l1 = [0], l2 = [0]
Output: [0]
```
**Example 3:**
```
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
```

#### [圖片來源:] https://leetcode.com/problems/add-two-numbers/

## 解題想法:
* 需考慮益位
    * 每次用餘數創建新node
    * 並將商留給next進行累加

## python:
``` python=
# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
    def insertNode(self,node):
        if self.next==None:
            self.next = ListNode(node)
        else:
            self.next.insertNode(node)
    def printList(self):
        array = []
        head = self
        while head:
            array.append(head.val)
            head = head.next
        print(array)

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        ans = ListNode(0)
        curNode = ans
        #考慮溢位
        carry=0
        while l1 or l2 or carry>0:
            if l1:
                carry+=l1.val
                l1 = l1.next
            if l2:
                carry+=l2.val
                l2 = l2.next
            curNode.next = ListNode(carry%10)
            curNode = curNode.next
            carry = carry//10
        return ans.next
if __name__ == '__main__':
    l1 = ListNode(2)
    l1.insertNode(4)
    l1.insertNode(3)
    l1.printList()
    l2 = ListNode(5)
    l2.insertNode(6)
    l2.insertNode(4)
    
    l2.printList()
    
    result = Solution()
    ans = result.addTwoNumbers(l1,l2)
    #print(ans)
    ans.printList()
#Input: l1 = [2,4,3], l2 = [5,6,4]
#Output: [7,0,8]
#Explanation: 342 + 465 = 807.
```
