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.
Tags: Linked List, Math
以链表表示一个数,低位在前,高位在后,所以题中的例子就是 342 + 465 = 807.
直接模拟计算就好
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
node := &ListNode{Val: 0, Next: nil}
n1, n2, tmp := l1, l2, node
sum := 0
for n1 != nil || n2 != nil {
sum /= 10
if n1 != nil {
sum += n1.Val
n1 = n1.Next
}
if n2 != nil {
sum += n2.Val
n2 = n2.Next
}
tmp.Next = &ListNode{Val: sum % 10}
tmp = tmp.Next
}
if sum/10 != 0 {
tmp.Next = &ListNode{Val: 1}
}
return node.Next
}
思路 2 ```go
```
如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:awesome-golang-algorithm