-
Notifications
You must be signed in to change notification settings - Fork 3
/
Lonely Integer.swift
40 lines (30 loc) · 1.12 KB
/
Lonely Integer.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
import Foundation
/*
* Complete the 'lonelyinteger' function below.
*
* The function is expected to return an INTEGER.
* The function accepts INTEGER_ARRAY a as parameter.
*/
func lonelyinteger(a: [Int]) -> Int {
var numbers: [Int] = a
var result: Int = numbers.removeFirst()
numbers.forEach {
result = result ^ $0
}
return result
}
let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!
guard let n = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }
guard let aTemp = readLine()?.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression) else { fatalError("Bad input") }
let a: [Int] = aTemp.split(separator: " ").map {
if let aItem = Int($0) {
return aItem
} else { fatalError("Bad input") }
}
guard a.count == n else { fatalError("Bad input") }
let result = lonelyinteger(a: a)
fileHandle.write(String(result).data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)