Given a Roman numeral string s, convert it to an integer. Roman numerals use I=1, V=5, X=10, L=50, C=100, D=500, M=1000. When a smaller value precedes a larger one, it is subtracted (e.g. IV=4, IX=9, CM=900).
s = "MCMXCIV"1994s = "LVIII"58i: get cur = map[s[i]]nxt = map[s[i+1]] or 0 if last charcur < nxt → res -= cur (subtractive: IV, IX, CM…)res after scanning all charsRoman numerals subtract when a smaller symbol precedes a larger one (IV, IX, XL, XC, CD, CM). The simple rule: compare cur with nxt. If cur < nxt → subtract; else → add. A single left-to-right pass handles all cases correctly in O(n).
Listing every special pair, like C M or X C, as its own case works, but it is easy to miss one. One simple rule covers all of them.
Look at each symbol and the one right after it. If the current value is smaller than the next value, subtract it. Otherwise, add it.
A smaller symbol before a larger one is subtracted. Comparing with the next symbol handles every special case at once.
Run the animation above on your own input, or watch the 1:27 video explanation of Roman to Integer with a dry run and Java code.