-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.swift
More file actions
48 lines (46 loc) · 944 Bytes
/
Solution.swift
File metadata and controls
48 lines (46 loc) · 944 Bytes
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
/*
Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
*/
import Foundation
func romanToInt(_ s: String) -> Int {
var previous = 0
var result = 0
for c in s {
var value = 0
switch c {
case "I":
value = 1
break
case "V":
value = 5
break
case "X":
value = 10
break
case "L":
value = 50
break
case "C":
value = 100
break
case "D":
value = 500
break
case "M":
value = 1000
break
default:
break
}
if previous < value {
result -= previous
} else {
result += previous
}
previous = value
}
result += previous
return result
}