-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path04_roman_to_integer.py
More file actions
63 lines (45 loc) · 1.19 KB
/
04_roman_to_integer.py
File metadata and controls
63 lines (45 loc) · 1.19 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
59
60
61
62
63
class Solution:
def romanToInt_method1(self, s: str) -> int:
dict = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
prev = 0
total = 0
for i in range(len(s)):
curr = dict[s[i]]
if curr > prev:
total += curr - 2 * prev
else:
total += curr
prev = curr
return total
def romanToInt_method2(self, s: str) -> int:
roman_map = {
'I': 1, 'V': 5, 'X': 10,
'L': 50, 'C': 100,
'D': 500, 'M': 1000
}
total = 0
prev_value = 0
for char in reversed(s):
value = roman_map[char]
if value < prev_value:
total -= value
else:
total += value
prev_value = value
return total
if __name__ == "__main__":
obj = Solution()
X = obj.romanToInt_method1("III")
print(X) # 3
Y = obj.romanToInt_method1("LVIII")
print(Y) # 58
Z = obj.romanToInt_method1("MCMXCIV")
print(Z) # 1994