Skip to content

Instantly share code, notes, and snippets.

@nthj
Created March 15, 2022 00:13
Show Gist options
  • Save nthj/49e7ed891a14e50a6234c25a1abc5bde to your computer and use it in GitHub Desktop.
Save nthj/49e7ed891a14e50a6234c25a1abc5bde to your computer and use it in GitHub Desktop.
Add Two Numbers
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
* Runtime: 8 ms, faster than 88.19% of Go online submissions for Add Two Numbers.
* Memory Usage: 4.3 MB, less than 100.00% of Go online submissions for Add Two Numbers.
*/
var one = ListNode{ Val: 1 }
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil && l2 == nil {
return nil
} else if l1 == nil {
return l2
} else if l2 == nil {
return l1
}
var sum int
var o *ListNode
sum = l1.Val + l2.Val
if sum > 9 {
o = &one
}
l1.Val = sum % 10
l1.Next = addTwoNumbers(
addTwoNumbers(l1.Next, l2.Next),
o,
)
return l1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment