forked from sashaaero/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
27 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
# https://leetcode.com/problems/roman-to-integer/ | ||
# Runtime: 52 ms, faster than 96.13% of Python3 online submissions for Roman to Integer. | ||
|
||
class Solution: | ||
def romanToInt(self, s: str) -> int: | ||
res = 0 | ||
values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} | ||
prev = None | ||
for sym in s: | ||
res += values[sym] | ||
if sym in ('D', 'M') and prev == 'C': | ||
res -= 200 | ||
elif sym in ('L', 'C') and prev == 'X': | ||
res -= 20 | ||
elif sym in ('V', 'X') and prev == 'I': | ||
res -= 2 | ||
prev = sym | ||
return res | ||
|
||
|
||
if __name__ == '__main__': | ||
s = Solution() | ||
assert s.romanToInt('III') == 3 | ||
assert s.romanToInt('IV') == 4 | ||
assert s.romanToInt('IX') == 9 | ||
assert s.romanToInt('LVIII') == 58 | ||
assert s.romanToInt('MCMXCIV') == 1994 |