# LeetCode: 2. 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 contain a single digit. Add the two numbers and return it as a linked list.

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

Example:

```Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
```

## 解法¶

### 按照加法运算的规则计算各个节点的值¶

• 将两个节点的值进行相加按进位加法得出新节点值，然后让进位的值参与下一个节点的计算即可。
```2 -> 4 -> 3 +
5 -> 6 -> 4 =
7 -> 0(10进一位) -> 8(7+1)
```

```# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
carry = 0

while l1 is not None or l2 is not None or carry > 0:
l1_val = 0
l2_val = 0
if l1 is not None:
l1_val = l1.val
l1 = l1.next
if l2 is not None:
l2_val = l2.val
l2 = l2.next

total = l1_val + l2_val + carry
carry = total // 10
val = total % 10

else:
node = ListNode(val)
pre.next = node
pre = node

```

```input: (5) + (5)
ouput: 0 -> 1
```