-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp2.go
More file actions
61 lines (50 loc) · 828 Bytes
/
p2.go
File metadata and controls
61 lines (50 loc) · 828 Bytes
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
type ListNode struct {
Val int
Next *ListNode
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
more := 0
res := new(ListNode)
head := res
s1, s2, s := 0, 0, 0
for l1 != nil || l2 != nil {
if l1 == nil {
s1 = 0
s2 = l2.Val
l2 = l2.Next
} else if l2 == nil {
s2 = 0
s1 = l1.Val
l1 = l1.Next
} else {
s1 = l1.Val
s2 = l2.Val
l1 = l1.Next
l2 = l2.Next
}
s = s1 + s2 + more
res.Val = s % 10
more = s / 10
if l1 == nil && l2 == nil {
if more == 0 {
res.Next = nil
} else {
res.Next = new(ListNode)
res = res.Next
res.Val = more
}
break
}
res.Next = new(ListNode)
res = res.Next
}
return head
}