LeetCode – 2. Add Two Numbers

題目連結: https://leetcode.com/problems/add-two-numbers/

參考解法:

https://leetcode.com/problems/add-two-numbers/discuss/1128713/Solution-Swift%3A-Add-Two-Numbers

https://leetcode.com/problems/add-two-numbers/discuss/412117/Swift-44ms

法ㄧ (p.s. 用L1 list當作最後的result list)

    func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        if l1 == nil { return l2 }
        else if l2 == nil { return l1 }
        else {
                var curPtr: ListNode? = nil
        	var ptr1 = l1
        	var ptr2 = l2
        	var carry = 0
        	while ptr1 != nil && ptr2 != nil {
        		let sum = (ptr1?.val ?? 0) + (ptr2?.val ?? 0) + carry
        		let val = sum % 10
        		carry = sum / 10
        		ptr1?.val = val
        		curPtr = ptr1
        		ptr1 = ptr1?.next
        		ptr2 = ptr2?.next
        	}

        	while ptr1 != nil {
        	        let sum = (ptr1?.val ?? 0) + carry
        	        let val = sum % 10
        		carry = sum / 10
        		ptr1?.val = val
        		curPtr = ptr1
        		ptr1 = ptr1?.next
        	}

        	while ptr2 != nil {
        	 	let sum = (ptr2?.val ?? 0) + carry
        	        let val = sum % 10
        		carry = sum / 10
        		let n = ListNode(val)
        		curPtr?.next = n
        		curPtr = curPtr?.next
        		ptr2 = ptr2?.next
        	}
        	if carry != 0 {
        	   	let n = ListNode(carry)
        		curPtr?.next = n
        	}
        	return l1
        }

法二: (Recursive) 參考自Ref

	var carry = 0
	func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
    	    if l1 == nil && l2 == nil && carry == 0 { return nil }
    	    let sum = (l1?.val ?? 0) + (l2?.val ?? 0) + carry
    	    let val = sum % 10
            carry = sum / 10
    	    return ListNode(val, addTwoNumbers(l1?.next, l2?.next))
	}