leetcode 2. 两数相加

题解

比较简单,遍历l1, l2进行相加,注意进位问题

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
var head, l3 *ListNode
c := 0
for l1 != nil || l2 != nil {
sum := c
if l1 != nil {
sum += l1.Val
l1 = l1.Next
}
if l2 != nil {
sum += l2.Val
l2 = l2.Next
}
c = sum / 10
tmp := &ListNode{sum % 10, nil}
if head == nil {
head = tmp
l3 = head
} else {
l3.Next = tmp
l3 = l3.Next
}
}
if c > 0 {
tmp := &ListNode{c, nil}
l3.Next = tmp
}
return head
}