Convert a Roman numeral into an integer. Normally the symbols are added from left to right, like V I I for 7. But a smaller symbol placed before a larger one is subtracted, like I V for 4.
DSA Animator › DSA Revision › Strings › Roman to Integer
Remember: a smaller symbol before a larger one is subtracted. Comparing with the next symbol handles every special case at once. The video solves Roman to Integer (LeetCode 13, Easy) with the Lookahead pattern from the Strings topic, and you can replay every step in the interactive Roman to Integer animation.
Convert a Roman numeral into an integer. Normally the symbols are added from left to right, like V I I for 7. But a smaller symbol placed before a larger one is subtracted, like I V for 4.
M, C, M, X, C, I, V is 1994. That is 1000, plus 900, plus 90, plus 4.
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.
M is 1000, and the next symbol is smaller, so add 1000. C is 100, but the next symbol is M, which is bigger, so subtract 100, giving 900. M adds 1000, for 1900. X is smaller than the C after it, so subtract 10, giving 1890. C adds 100, for 1990. I is smaller than V, so subtract 1, then V adds 5. The total is 1994.
In code, map each symbol to its value. For each index, compare its value with the value after it. Subtract when it is smaller, otherwise add. One pass, so it's O of n time and O of 1 space.
Remember: a smaller symbol before a larger one is subtracted. Comparing with the next symbol handles every special case at once.