添加内容

This commit is contained in:
YDZ
2020-08-08 09:17:26 +08:00
parent 5015cc6b7b
commit fdba30f0c4
734 changed files with 4024 additions and 2129 deletions

View File

@ -0,0 +1,89 @@
# [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 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 个逆序的链表,要求从低位开始相加,得出结果也逆序输出,返回值是逆序结果链表的头结点。
## 解题思路
需要注意的是各种进位问题。
极端情况,例如
```
Input: (9 -> 9 -> 9 -> 9 -> 9) + (1 -> )
Output: 0 -> 0 -> 0 -> 0 -> 0 -> 1
```
为了处理方法统一,可以先建立一个虚拟头结点,这个虚拟头结点的 Next 指向真正的 head这样 head 不需要单独处理,直接 while 循环即可。另外判断循环终止的条件不用是 p.Next = nil这样最后一位还需要额外计算循环终止条件应该是 p != nil。
## 代码
```go
package leetcode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil || l2 == nil {
return nil
}
head := &ListNode{Val: 0, Next: nil}
current := head
carry := 0
for l1 != nil || l2 != nil {
var x, y int
if l1 == nil {
x = 0
} else {
x = l1.Val
}
if l2 == nil {
y = 0
} else {
y = l2.Val
}
current.Next = &ListNode{Val: (x + y + carry) % 10, Next: nil}
current = current.Next
carry = (x + y + carry) / 10
if l1 != nil {
l1 = l1.Next
}
if l2 != nil {
l2 = l2.Next
}
}
if carry > 0 {
current.Next = &ListNode{Val: carry % 10, Next: nil}
}
return head.Next
}
```