Skip to content

Commit 51805ad

Browse files
committed
add roman to integer
1 parent 7eaee5a commit 51805ad

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

py3/easy/roman_to_integer/link

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
https://leetcode.com/problems/roman-to-integer/
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution(object):
2+
def romanToInt(self, s):
3+
table = {"-": 100500, "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
4+
num = 0
5+
prev = "-"
6+
cache = 0
7+
for c in s:
8+
if c == prev:
9+
cache += table[c]
10+
elif table[c] < table[prev]:
11+
num += cache
12+
cache = table[c]
13+
prev = c
14+
else:
15+
num -= cache
16+
cache = table[c]
17+
prev = c
18+
return num + cache
19+
20+
21+
def main():
22+
a = input()
23+
print(Solution().romanToInt(a))
24+
25+
26+
if __name__ == "__main__":
27+
main()
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"input": "IV\n",
3+
"output": "4"
4+
}

0 commit comments

Comments
 (0)