forked from alqamahjsr/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2_Add_Two_Numbers.swift
More file actions
executable file
·60 lines (41 loc) · 1.35 KB
/
Copy path2_Add_Two_Numbers.swift
File metadata and controls
executable file
·60 lines (41 loc) · 1.35 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//: Playground - noun: a place where people can play
import UIKit
//: Problem: https://leetcode.com/problems/add-two-numbers/
// 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
}
}
public class Solution_2 {
public init() {
}
public func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var dummyHead = ListNode(0)
var p:ListNode? = l1
var q:ListNode? = l2
var carry = 0
var currentNode = dummyHead
while ((p != nil) || (q != nil)) {
let x:Int = p?.val ?? Int(0) // Doc: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html
let y:Int = q?.val ?? Int(0)
let sum = x + y + carry
carry = sum/10
currentNode.next = ListNode(sum%10)
currentNode = currentNode.next!
if (p != nil) {
p = p?.next
}
if (q != nil) {
q = q?.next
}
}
if carry > 0 {
currentNode.next = ListNode(carry)
}
return dummyHead.next
}
}