Roman to Integer

Medium · rating 1150 · strings, implementation

Read a Roman numeral (using symbols I V X L C D M, valid subtractive forms like IV and IX included). Print its integer value.

Constraints: 1 ≤ value ≤ 3999

Editorial

Approach

Map each symbol to its value and scan left to right. Normally you add, but in subtractive pairs (like IV = 4 or IX = 9) a smaller value sits before a larger one — so if the current symbol's value is less than the next symbol's, subtract it instead of adding.

val = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
total = 0
for i, c in enumerate(s):
    if i+1 < len(s) and val[c] < val[s[i+1]]:
        total -= val[c]
    else:
        total += val[c]
return total

Complexity

Time: O(n). Space: O(1).

Open Roman to Integer in Code Arena →