|
| 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