Skip to content

Commit ad01e5b

Browse files
author
Yi Gu
committed
[Math] add Solution to Roman to Integer
1 parent 2cb600d commit ad01e5b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Math/RomanToInteger.swift

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/roman-to-integer/
3+
* Primary idea: Iterate through end to start, add or minus according to different situations
4+
* Time Complexity: O(n), Space Complexity: O(n)
5+
*
6+
*/
7+
8+
class RomanToInteger {
9+
func romanToInt(s: String) -> Int {
10+
let dict = initDict()
11+
let chars = [Character](s.characters.reverse())
12+
var res = 0
13+
14+
for i in 0 ..< chars.count {
15+
guard let current = dict[String(chars[i])] else {
16+
return res
17+
}
18+
if i > 0 && current < dict[String(chars[i - 1])] {
19+
res -= current
20+
} else {
21+
res += current
22+
}
23+
}
24+
25+
return res
26+
}
27+
28+
private func initDict() -> [String: Int] {
29+
var dict = [String: Int]()
30+
31+
dict["I"] = 1
32+
dict["V"] = 5
33+
dict["X"] = 10
34+
dict["L"] = 50
35+
dict["C"] = 100
36+
dict["D"] = 500
37+
dict["M"] = 1000
38+
39+
return dict
40+
}
41+
}

0 commit comments

Comments
 (0)