forked from JediXL/LeetCodeByPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13Roman2Integer.py
126 lines (113 loc) · 3.21 KB
/
13Roman2Integer.py
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
roman = s
num = 0
rlen = len(roman)
if rlen == 0:
return 0
i = 0
while i < rlen:
if roman[i] == "M":
num = num + 1000
i = i + 1
continue
if roman[i] == "C":
if i + 1 < rlen:
if roman[i+1] == "M":
num = num + 900
i = i + 2
continue
elif roman[i+1] == "D":
num = num + 400
i = i + 2
continue
else:
num = num + 100
i = i + 1
continue
else:
num = num + 100
i = i + 1
continue
if roman[i] == "D":
num = num + 500
i = i + 1
continue
if roman[i] == "X":
if i + 1 < rlen:
if roman[i+1] == "C":
num = num + 90
i = i + 2
continue
elif roman[i+1] == "L":
num = num + 40
i = i + 2
continue
else:
num = num + 10
i = i + 1
continue
else:
num = num + 10
i = i + 1
continue
if roman[i] == "L":
num = num + 50
i = i + 1
continue
if roman[i] == "I":
if i + 1 < rlen:
if roman[i+1] == "X":
num = num + 9
i = i + 2
continue
elif roman[i+1] == "V":
num = num + 4
i = i + 2
continue
else:
num = num + 1
i = i + 1
continue
else:
num = num + 1
i = i + 1
continue
if roman[i] == "V":
num = num + 5
i = i + 1
continue
return num
class Solution1:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
roman_id = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
c = 0
num = 0
for i in range(len(s) - 1, -1, -1):
j = roman_id[s[i]]
# 如果当前字符小于上次迭代的字符,那么属于特殊请求(e.g.,CD,IV..)
if j < c:
num -= j
# 否则直接相加
if j >= c:
num += j
c = j
return num
s = Solution1()
print(s.romanToInt("MCDLXXVI"))