MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / addTwoNumbers

Function addTwoNumbers

add_two_numbers_2/solution.go:8–48  ·  view source on GitHub ↗
(l1 *structures.ListNode, l2 *structures.ListNode)

Source from the content-addressed store, hash-verified

6)
7
8func addTwoNumbers(l1 *structures.ListNode, l2 *structures.ListNode) *structures.ListNode {
9 num1 := depthFirstNum(l1)
10 num2 := depthFirstNum(l2)
11
12 var sum big.Int
13 sum.Add(num1, num2)
14
15 // single digit sum
16 if len(sum.String()) == 1 {
17 return &structures.ListNode{
18 Val: int(sum.Int64()),
19 Next: nil,
20 }
21 }
22
23 var sumList *structures.ListNode
24 var current *structures.ListNode
25
26 for sum.String() != "0" {
27 var lastDigit big.Int
28 lastDigit.Mod(&sum, big.NewInt(10))
29
30 node := &structures.ListNode{
31 Val: int(lastDigit.Int64()),
32 Next: nil,
33 }
34 if sumList == nil {
35 sumList = node
36 }
37 if current == nil {
38 current = node
39 } else {
40 current.Next = node
41 current = current.Next
42 }
43
44 sum.Div(&sum, big.NewInt(10))
45 }
46
47 return sumList
48}
49
50func depthFirstNum(l *structures.ListNode) *big.Int {
51 if l == nil {

Callers 1

Test_addTwoNumbersFunction · 0.85

Calls 1

depthFirstNumFunction · 0.85

Tested by 1

Test_addTwoNumbersFunction · 0.68