-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaddTwoNumbers.go
61 lines (53 loc) · 1.07 KB
/
addTwoNumbers.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
package demo
func echoList(str string, node *ListNode) {
print(str, "`")
var tmp *ListNode
tmp = node
for tmp != nil {
print(tmp.Val, " ")
tmp = tmp.Next
}
println("`")
}
func GenerateList(numbers []int) *ListNode {
if len(numbers) < 1 {
return nil
}
ret := &ListNode{Val: numbers[0], Next: nil}
var tmp *ListNode
tmp = ret
for i := 1; i < len(numbers); i++ {
tmp.Next = &ListNode{Val: numbers[i], Next: nil}
tmp = tmp.Next
}
return ret
}
func addTwoNumbers(one, two *ListNode) *ListNode {
if two == nil {
return one
}
if one == nil {
one = &ListNode{0, nil}
}
var carry, lastNodeVal, tmpSum int
var tmpOne, tmpTwo, ret *ListNode
tmpOne, tmpTwo = one, two
ret = tmpTwo
for tmpOne != nil || tmpTwo != nil || carry > 0 {
if tmpOne != nil {
tmpSum += tmpOne.Val
tmpOne = tmpOne.Next
}
tmpSum += tmpTwo.Val
tmpSum += carry
lastNodeVal = tmpSum % 10
carry = tmpSum / 10
tmpSum = 0
if tmpTwo.Next == nil && (tmpOne != nil || carry > 0) {
tmpTwo.Next = &ListNode{}
}
tmpTwo.Val = lastNodeVal
tmpTwo = tmpTwo.Next
}
return ret
}