-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd.go
89 lines (71 loc) · 1.19 KB
/
add.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
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func (l *ListNode) String() string {
s := ""
for l != nil {
if l.Next == nil {
s += fmt.Sprintf("(%d)", l.Val)
} else {
s += fmt.Sprintf("(%d)→", l.Val)
}
l = l.Next
}
return s
}
func NewList(values ...int) *ListNode {
var head *ListNode
var current *ListNode
for _, v := range values {
node := &ListNode{Val: v}
if head == nil {
head = node
} else {
current.Next = node
}
current = node
}
return head
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
var result *ListNode
var current *ListNode
var carry int
for l1 != nil || l2 != nil {
var v1, v2 int
if l1 != nil {
v1 = l1.Val
l1 = l1.Next
}
if l2 != nil {
v2 = l2.Val
l2 = l2.Next
}
node := &ListNode{Val: v1 + v2 + carry}
carry = 0
if node.Val >= 10 {
node.Val -= 10
carry = 1
}
if result == nil {
result = node
} else {
current.Next = node
}
current = node
}
if carry > 0 {
current.Next = &ListNode{Val: carry}
}
return result
}
func main() {
a := NewList(2, 4, 3)
b := NewList(5, 6, 4)
fmt.Println(a)
fmt.Println(b)
fmt.Println(addTwoNumbers(a, b))
}