Last active
January 7, 2020 11:06
-
-
Save spurscho/32a5b40b9098727063c56bc8e3763313 to your computer and use it in GitHub Desktop.
addTwoNumbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var p1: ListNode? = l1 | |
var p2: ListNode? = l2 | |
var resultNode: ListNode? = ListNode(0) | |
let head = resultNode | |
var carry = 0 | |
while p1 != nil || p2 != nil || carry > 0 { | |
let val1 = p1?.val ?? 0 | |
let val2 = p2?.val ?? 0 | |
let sum = val1 + val2 + carry | |
let value = sum % 10 | |
carry = sum / 10 | |
resultNode?.next = ListNode(value) | |
resultNode = resultNode?.next | |
p1 = p1?.next | |
p2 = p2?.next | |
} | |
return head?.next |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment