summaryrefslogtreecommitdiff
path: root/twosum/twosum.go
blob: ca931041a594c9c764f73a7c4809bb2524ee9c0d (plain)
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
package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	carry := 0
	var output, co *ListNode
	c1 := l1
	c2 := l2
	for {
		if c1 != nil && c2 != nil {
			sum := c1.Val + c2.Val + carry
			carry = sum / 10
			rem := sum % 10
			c1.Val = rem
			c2.Val = rem

			if c1.Next == nil && c2.Next == nil {
				if carry > 0 {
					c1.Next = &ListNode{
						Val: 1,
					}
					carry = 0
				}
			}

			c1 = c1.Next
			c2 = c2.Next
			continue
		}

		if c1 != nil {
			output = l1
			co = c1
			break
		} else if c2 != nil {
			output = l2
			co = c2
			break
		} else {

			output = l1
			break
		}
	}

	if co != nil {
		for {
			sum := co.Val + carry
			carry = sum / 10
			rem := sum % 10

			co.Val = rem
			if co.Next == nil {
				if carry > 0 {
					co.Next = &ListNode{
						Val: 1,
					}
				}
				break
			}
			co = co.Next
		}
	}

	return output
}

func makeList(list []int) *ListNode {
	output := &ListNode{
		Val:  list[0],
		Next: nil,
	}
	current := output
	for _, n := range list[1:] {
		node := &ListNode{
			Val: n,
		}
		current.Next = node
		current = node
	}

	return output
}

func printList(node *ListNode) {
	for {
		if node == nil {
			break
		}

		fmt.Print(node.Val)
		node = node.Next
	}
	fmt.Println()
}

func main() {
	// Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
	// Output: [8,9,9,9,0,0,0,1]
	l1 := makeList([]int{9, 9, 9, 9, 9, 9, 9})
	l2 := makeList([]int{9, 9, 9, 9})
	printList(l1)
	printList(l2)

	printList(addTwoNumbers(l1, l2))
}