forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AddTwoNumbers.swift
41 lines (36 loc) · 1.04 KB
/
AddTwoNumbers.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Question Link: https://leetcode.com/problems/add-two-numbers/
* Primary idea: use carry and iterate through both linked lists
* Time Complexity: O(n), Space Complexity: O(1)
*
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class AddTwoNumbers {
func addTwoNumbers(l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var carry = 0, l1 = l1, l2 = l2
let dummy = ListNode(0)
var node = dummy
while l1 != nil || l2 != nil || carry != 0 {
if l1 != nil {
carry += l1!.val
l1 = l1!.next
}
if l2 != nil {
carry += l2!.val
l2 = l2!.next
}
node.next = ListNode(carry % 10)
node = node.next!
carry = carry / 10
}
return dummy.next
}
}