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

Function addTwoNumbers2

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

Source from the content-addressed store, hash-verified

57}
58
59func addTwoNumbers2(l1 *structures.ListNode, l2 *structures.ListNode) *structures.ListNode {
60 carry := 0
61 sumList := &structures.ListNode{
62 Val: 0,
63 Next: nil,
64 }
65 frontSumList := sumList
66
67 for l1 != nil || l2 != nil {
68 // calculate sum and carry values
69 l1Val := 0
70 l2Val := 0
71 if l1 != nil {
72 l1Val = l1.Val
73 l1 = l1.Next
74 }
75 if l2 != nil {
76 l2Val = l2.Val
77 l2 = l2.Next
78 }
79
80 sum := l1Val + l2Val + carry
81 carry = sum / 10
82 sumList.Val = sum % 10
83
84 // no more list to process, but carry is not 0
85 if l1 == nil && l2 == nil && carry > 0 {
86 sumList.Next = &structures.ListNode{
87 Val: carry,
88 Next: nil,
89 }
90 }
91
92 // one or both lists still can be processed
93 if l1 != nil || l2 != nil {
94 sumList.Next = &structures.ListNode{
95 Val: 0,
96 Next: nil,
97 }
98 sumList = sumList.Next
99 }
100 }
101
102 return frontSumList
103}

Callers 1

Test_addTwoNumbersFunction · 0.85

Calls

no outgoing calls

Tested by 1

Test_addTwoNumbersFunction · 0.68