# Golang 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.

## 思路分析

• 两个整数逆序存储，低位向高位有进位时不再是向前而是向后进位。

• 两个整数不一定有相同的位数，所以遍历链表时要判断是否遍历结束，如果结束，就将其相应位置为0。

• 两个整数的最高位相加可能产生进位。

## 解决方案

sum等于两个整数对应位相加再加上低位进位，sum向高位的进位 carry = sum / 10，此时结果链表新增一个节点，current.Val = sum % 10即 current.Next = new ListNode(sum % 10)。这样便完成了一次加法和进位操作，结果链表和两个存储整数的链表的指针向后移动一位，重复之前的加法和进位操作，直到两个整数遍历结束且不存在进位。

## 代码

```/**
* type ListNode struct {
*     Val int
*     Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
carry := 0
for l1 != nil || l2 != nil || carry > 0 {
sum := carry
if l1 != nil {
sum += l1.Val
l1 = l1.Next
}
if l2 != nil {
sum += l2.Val
l2 = l2.Next
}
carry = sum / 10
current.Next = new(ListNode)
current.Next.Val = sum % 10
current = current.Next
}