-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
157 lines (134 loc) · 2.34 KB
/
main.go
File metadata and controls
157 lines (134 loc) · 2.34 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package main
import (
"log"
)
// list Node
type ListNode struct {
// value type int
Val int
// Next Node *ListNode
Next *ListNode
}
/*
*
*
* insert new node to last node
*
* args :
* last *ListNode
* val int
*
* return value:
* *ListNode
*
*
*/
func insert(last *ListNode, val int) *ListNode {
temp := new(ListNode)
temp.Val = val
temp.Next = nil
last.Next = temp
return last.Next
}
/*
*
*
* sum two list numbers
*
* args :
* l1, l2 *ListNode
*
* return value:
* *ListNode
*
*
*/
func addTwoNumbers(l1, l2 *ListNode) *ListNode {
// make response node
// make c ( carry )
// sum value two int
// first setup sum two value l1.Val + l2.Val
res, c, s := &ListNode{Val: l1.Val + l2.Val}, 0, 0
// make temp1 and temp2
// we get first number from two list
// because we need next node
t1, t2 := l1.Next, l2.Next
// if res.Val ( l1.Val + l2.Val ) > 9
// we have carry
if res.Val > 9 {
c = res.Val / 10
res.Val = res.Val % 10
}
// make temp for response value
temp := res
// loop to t1 and t2
// if t1 or t2 equal nil
// loop break
for ; t1 != nil && t2 != nil; t1, t2 = t1.Next, t2.Next {
// sum tow value t1.Val + t2.Val + c
s = t1.Val + t2.Val + c
// make carry zero
c = 0
// check s > 0 orn ot
if s > 9 {
// change c and s
// make s less 10 ( s % 10)
// setup new carry s / 10
c, s = s/10, s%10
}
// and insert
temp = insert(temp, s)
}
// this loop for insert
// value form t1 != nil
for ; t1 != nil; t1 = t1.Next {
s = t1.Val + c
c = 0
if s > 9 {
c, s = s/10, s%10
}
temp = insert(temp, s)
}
// this loop for insert
// value form t2 != nil
for ; t2 != nil; t2 = t2.Next {
s = t2.Val + c
c = 0
if s > 9 {
c, s = s/10, s%10
}
temp = insert(temp, s)
}
// if c != 0 insert New value to list
if c != 0 {
temp = insert(temp, c)
}
return res
}
func main() {
// very simple test
l1 := &ListNode{Val: 2}
l2 := &ListNode{Val: 5}
t1, t2 := l1, l2
for _, v := range []int{4, 3} {
t1 = insert(t1, v)
}
for _, v := range []int{6, 4} {
t2 = insert(t2, v)
}
ans := addTwoNumbers(l1, l2)
trueAns, i := []int{7, 0, 8}, 0
for ; ans != nil; ans = ans.Next {
if ans.Val != trueAns[i] {
log.Fatal("Wrong Answer!")
}
i++
if i >= len(trueAns) {
break
}
}
if ans != nil && ans.Next != nil {
log.Fatal("Wrong Answer!")
}
log.Println("True Answer!")
}