[Leetcode X Golang] Study Note 02


By: Axe 2019-10-01

Problem: 2. Add Two Numbers

Solution:

When there is an official solution in leetcode, I will omit this section in the future.

Code:

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	head := &ListNode{}
	curr := head
	carry := 0
	p := l1
	q := l2
	for p != nil || q != nil {
		x := 0
		if p != nil {
			x = p.Val
		}
		y := 0
		if q != nil {
			y = q.Val
		}
		sum := x + y + carry
		carry = sum / 10
		mod := sum % 10

		curr.Next = &ListNode{Val: mod}
		curr = curr.Next

		if p != nil {
			p = p.Next
		}

		if q != nil {
			q = q.Next
		}
	}

	if carry > 0 {
		curr.Next = &ListNode{Val: carry}
	}

	return head.Next
}

Notes:

  • to create an instance of struct, you have to specify the key if not all keys will be instantiated
  • golang doesn't have ternary condition
  • the solution is 10x faster than my previous python submission