Skip to content

Instantly share code, notes, and snippets.

@alissonbrunosa
Last active August 11, 2020 15:44
Show Gist options
  • Save alissonbrunosa/6e796e18c172845300c6810fd18a6c6c to your computer and use it in GitHub Desktop.
Save alissonbrunosa/6e796e18c172845300c6810fd18a6c6c to your computer and use it in GitHub Desktop.
/*
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
return sumNodes(l1, l2, 0)
}
func sumNodes(l1 *ListNode, l2 *ListNode, rest int) *ListNode {
if l1 == nil && l2 == nil {
if rest > 0 {
return &ListNode{Val: rest}
}
return nil
}
if l1 != nil && l2 == nil {
return sumNodes(l1, &ListNode{Val: rest}, 0)
}
if l2 != nil && l1 == nil {
return sumNodes(l2, &ListNode{Val: rest}, 0)
}
node := &ListNode{}
val := l1.Val + l2.Val + rest
node.Val = val % 10
node.Next = sumNodes(l1.Next, l2.Next, val/10)
return node
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment