leetcode-hot-(2/100)

zhangshaos · · 799 次点击 · · 开始浏览

2/100-两数相加

go to leetcode

分析解答

``````func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
// 1.for each reverse-list l1, l2:
//      new node's val = l1.val + l2.val + carry(初值为0)
//      carry = new carry
// 2.handle left reverse-list
var (
carry = 0
)
p1, p2 := l1, l2
for p1 != nil && p2 != nil {
tail = new(ListNode)
} else {
tail.Next = new(ListNode)
tail = tail.Next
}
sum := p1.Val + p2.Val + carry
tail.Val = sum % 10
carry = sum / 10
p1 = p1.Next
p2 = p2.Next
}
for p1 != nil {
tail.Next = new(ListNode)
tail = tail.Next
sum := p1.Val + carry
tail.Val = sum % 10
carry = sum / 10
p1 = p1.Next
}
for p2 != nil {
tail.Next = new(ListNode)
tail = tail.Next
sum := p2.Val + carry
tail.Val = sum % 10
carry = sum / 10
p2 = p2.Next
}
if carry != 0 {
tail.Next = new(ListNode)
tail = tail.Next
tail.Val = carry
carry = 0
}
}``````

反思

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

2/100-两数相加

go to leetcode

分析解答

``````func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
// 1.for each reverse-list l1, l2:
//      new node's val = l1.val + l2.val + carry(初值为0)
//      carry = new carry
// 2.handle left reverse-list
var (
carry = 0
)
p1, p2 := l1, l2
for p1 != nil && p2 != nil {
tail = new(ListNode)
} else {
tail.Next = new(ListNode)
tail = tail.Next
}
sum := p1.Val + p2.Val + carry
tail.Val = sum % 10
carry = sum / 10
p1 = p1.Next
p2 = p2.Next
}
for p1 != nil {
tail.Next = new(ListNode)
tail = tail.Next
sum := p1.Val + carry
tail.Val = sum % 10
carry = sum / 10
p1 = p1.Next
}
for p2 != nil {
tail.Next = new(ListNode)
tail = tail.Next
sum := p2.Val + carry
tail.Val = sum % 10
carry = sum / 10
p2 = p2.Next
}
if carry != 0 {
tail.Next = new(ListNode)
tail = tail.Next
tail.Val = carry
carry = 0
}