Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 51857ab

Browse files
committed
[20230415] Solve easy problem
1 parent 2f50e4b commit 51857ab

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# 13. Roman to Integer
2+
# https://leetcode.com/problems/roman-to-integer/description/
3+
4+
5+
class Solution:
6+
def romanToInt(self, s: str) -> int:
7+
d = {'I' : 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
8+
9+
i = 0
10+
result = 0
11+
12+
while i < len(s) - 1:
13+
c = s[i]
14+
if c == 'I' and (s[i+1] == 'V' or s[i+1] == 'X'):
15+
result += d[s[i+1]] - 1
16+
i += 2
17+
continue
18+
elif c == 'X' and (s[i+1] == 'L' or s[i+1] == 'C'):
19+
result += d[s[i+1]] - 10
20+
i += 2
21+
continue
22+
elif c == 'C' and (s[i+1] == 'D' or s[i+1] == 'M'):
23+
result += d[s[i+1]] - 100
24+
i += 2
25+
continue
26+
result += d[c]
27+
i += 1
28+
29+
if i <= len(s) - 1:
30+
result += d[s[i]]
31+
return result

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /