• API
• FAQ
• Tools
• Archive
daily pastebin goal
10%
SHARE
TWEET

# Untitled

a guest May 27th, 2018 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. //struct we will use for Linked list
2. type ListNode struct {
3.     Val  int
4.     Next *ListNode
5. }
6.
7. //the function that puts it all together
8. func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
9.     n1 := createNumber(l1)
10.     n2 := createNumber(l2)
11.
12.     sum := n1 + n2
13.
14.     fmt.Printf("%d + %d = %d \n", n1, n2, sum)
15.
17. }
18.
19. //create number from reversed linked-list
20. func createNumber(l *ListNode) int {
21.     val := l.Val
22.     decimalCount := 1
23.     for l.Next != nil { //iterate until nil
24.         l = l.Next
25.         computation := (l.Val * power(10, decimalCount))
26.         val += computation
27.         decimalCount++
28.     }
29.     return val
30. }
31.
32. //create linked-list from int
33. func createLinkedList(n int) *ListNode {
34.     head := ListNode{
35.         Val:  int(n % 10),
36.         Next: nil,
37.     }
38.
39.     var currentNode *ListNode
40.     currentNode = &head
41.
42.     for n > 0 {
43.         n = n / 10
44.         nextNode := ListNode{
45.             Val:  int(n % 10),
46.             Next: nil,
47.         }
48.         if n == 0 {
49.             break
50.         }
51.         currentNode.Next = &nextNode
52.         currentNode = &nextNode
53.     }
55. }
56.
57. //debug printing function if you need it!
58. func printLinkedList(l *ListNode) {
59.     i := 1
60.     for l != nil { //iterate until nil
61.         fmt.Printf("%v: %v \n", i, l.Val)
62.         i++
63.         l = l.Next
64.     }
65. }
66.
67. //helper function for exponents
68. func power(base int, power int) int {
69.     val := 1
70.     for i := 0; i < power; i++ {
71.         val *= base
72.     }
73.     return val
74. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top