To convert a Roman numeral to an integer, we need to carefully process the characters from left to right.
Understanding Roman Numerals
Each Roman character represents a fixed value. For example, I = 1
, V = 5
, X = 10
, etc. Normally, you just add these values together. So VIII
= 5 + 1 + 1 + 1 = 8.
But Wait – Some Subtractive Cases
Sometimes a smaller value appears before a larger one, which means we subtract instead of add. For example:
IV
= 4 (5 - 1)
IX
= 9 (10 - 1)
XL
= 40 (50 - 10)
So, while scanning from left to right, if the current character has a value less than the next, we subtract it. Otherwise, we add it.
How This Works in Practice
Let’s take MCMXCIV
as an example:
M
= 1000 (add)
CM
= 900 (100 before 1000 → subtract 100)
XC
= 90 (10 before 100 → subtract 10)
IV
= 4 (1 before 5 → subtract 1)
Total: 1000 + 900 + 90 + 4 = 1994
What Happens with an Empty String?
If the input is empty, we simply return 0
. There’s nothing to convert.
Conclusion
This approach is both simple and efficient. By carefully comparing each character with the next one, we can accurately compute the total integer value. It works in O(n) time where n
is the length of the Roman numeral.