Skip to content

Instantly share code, notes, and snippets.

@lkrych
Created May 23, 2018 01:57
Show Gist options
  • Save lkrych/3e4ed8fca9eddcc7e50be85c4b48ac7f to your computer and use it in GitHub Desktop.
Save lkrych/3e4ed8fca9eddcc7e50be85c4b48ac7f to your computer and use it in GitHub Desktop.
//struct we will use for Linked list
type ListNode struct {
Val int
Next *ListNode
}
//the function that puts it all together
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
n1 := createNumber(l1)
n2 := createNumber(l2)
sum := n1 + n2
fmt.Printf("%d + %d = %d \n", n1, n2, sum)
return createLinkedList(int64(sum))
}
//create number from reversed linked-list
func createNumber(l *ListNode) int {
val := l.Val
decimalCount := 1
for l.Next != nil { //iterate until nil
l = l.Next
computation := (l.Val * power(10, decimalCount))
val += computation
decimalCount++
}
return val
}
//create linked-list from int
func createLinkedList(n int) *ListNode {
head := ListNode{
Val: int(n % 10),
Next: nil,
}
var currentNode *ListNode
currentNode = &head
for n > 0 {
n = n / 10
nextNode := ListNode{
Val: int(n % 10),
Next: nil,
}
if n == 0 {
break
}
currentNode.Next = &nextNode
currentNode = &nextNode
}
return &head
}
//debug printing function if you need it!
func printLinkedList(l *ListNode) {
i := 1
for l != nil { //iterate until nil
fmt.Printf("%v: %v \n", i, l.Val)
i++
l = l.Next
}
}
//helper function for exponents
func power(base int, power int) int {
val := 1
for i := 0; i < power; i++ {
val *= base
}
return val
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment