Skip to content

Commit 3429569

Browse files
committed
Add Add :) Two Numbers solution
1 parent b4359bc commit 3429569

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed

add_two_numbers.go

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"strconv"
6+
"strings"
7+
)
8+
9+
type ListNode struct {
10+
Val int
11+
Next *ListNode
12+
}
13+
14+
func walk (l *ListNode, a *string) {
15+
v := l.Val
16+
*a = *a + fmt.Sprintf("%d", v)
17+
18+
if l.Next != nil {
19+
walk(l.Next, a)
20+
}
21+
}
22+
23+
func extendLinkedList(ln *ListNode, acc []string, ci int) {
24+
cmp := len(acc) - ci - 1
25+
iSum, _ := strconv.ParseInt(acc[cmp], 10, 32)
26+
ln.Val = int(iSum)
27+
28+
if cmp != 0 {
29+
next := ListNode{}
30+
ln.Next = &next
31+
extendLinkedList(ln.Next, acc, ci + 1)
32+
}
33+
}
34+
35+
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
36+
acc1 := ""
37+
acc2 := ""
38+
39+
walk(l1, &acc1)
40+
walk(l2, &acc2)
41+
42+
lng := acc1
43+
srt := acc2
44+
if len(acc1) < len(acc2) {
45+
lng = acc2
46+
srt = acc1
47+
}
48+
49+
sumStr := ""
50+
carry := 0
51+
for i := 0; i <= len(lng); i ++ {
52+
if i == len(lng) {
53+
if carry > 0 {
54+
sumStr = fmt.Sprintf("%d", carry) + sumStr
55+
}
56+
} else {
57+
var vs, vl string
58+
59+
if i < len(srt) {
60+
vs = string(srt[i])
61+
}
62+
63+
vl = string(lng[i])
64+
ds, _ := strconv.Atoi(vs)
65+
dl, _ := strconv.Atoi(vl)
66+
67+
sI := ds + dl + carry
68+
carry = sI / 10
69+
sI = sI % 10
70+
71+
fmt.Printf("\n Index: %d ::: short %d + long %d ==> %d;; carry: %d", i, ds, dl, sI, carry)
72+
sumStr = fmt.Sprintf("%d", sI) + sumStr
73+
}
74+
}
75+
76+
fmt.Printf("\n FINAL SUM::: %s", sumStr)
77+
sumSl := strings.Split(sumStr, "")
78+
79+
lnSum := ListNode{}
80+
extendLinkedList(&lnSum, sumSl, 0)
81+
82+
return &lnSum
83+
}
84+
85+
func extendTestCaseLinkedList(ln *ListNode, acc []int, ci int) {
86+
iSum := acc[ci]
87+
ln.Val = int(iSum)
88+
89+
if ci < len(acc) - 1 {
90+
next := ListNode{}
91+
ln.Next = &next
92+
extendTestCaseLinkedList(ln.Next, acc, ci + 1)
93+
}
94+
}
95+
96+
func main() {
97+
// Generated Test Case
98+
test1 := []int{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}
99+
test2 := []int{5,6,4}
100+
101+
var listNode1, listNode2 ListNode
102+
extendTestCaseLinkedList(&listNode1, test1, 0)
103+
extendTestCaseLinkedList(&listNode2, test2, 0)
104+
105+
addTwoNumbers(&listNode1, &listNode2)
106+
}

0 commit comments

Comments
 (0)