-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathContents.swift
73 lines (56 loc) · 1.7 KB
/
Contents.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import Foundation
precedencegroup LongArrowPrecedence {
associativity: left
higherThan: AssignmentPrecedence
}
infix operator ~>: LongArrowPrecedence
class Node: CustomStringConvertible{
var description: String {
if next == nil { return "\(value)" }
return "\(value) ~> \(next!.description)"
}
var next: Node?
var value: Int
init(_ value: Int) {
self.value = value
}
static func ~>(lhs: Node, rhs: Node) -> Node {
lhs.next = rhs
return rhs
}
}
/*
This problem was asked by Microsoft.
Let's represent an integer in a linked list format by having each node represent a digit in the number. The nodes make up the number in reversed order.
For example, the following linked list:
1 -> 2 -> 3 -> 4 -> 5
is the number 54321.
Given two linked lists in this format, return their sum in the same linked list format.
For example, given
9 -> 9
5 -> 2
return 124 (99 + 25) as:
4 -> 2 -> 1
*/
//time O(n)
//space O(n)
func sum(left: Node, right: Node) -> Node {
return sumHelper(left: left, right: right, additionalValue: 0)!
}
func sumHelper(left: Node?, right: Node?, additionalValue: Int) -> Node? {
guard left != nil
|| right != nil
|| additionalValue != 0
else { return nil }
let lValue = left?.value ?? 0
let rValue = right?.value ?? 0
let result = lValue + rValue + additionalValue
let resultNode = Node(result % 10)
resultNode.next = sumHelper(left: left?.next, right: right?.next, additionalValue: result / 10)
return resultNode
}
let left = Node(9)
left ~> Node(2) ~> Node(3) //329
let right = Node(1)
right ~> Node(2) ~> Node(10) //1021
sum(left: left, right: right) //1350