Easy · Subtractive Scan
Understand → Visualise → Practice.
Convert a valid Roman numeral to its integer value.
Add each numeral's value, except when it is smaller than the numeral that follows it (as in IV or XC); then subtract it.
I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000.
If the current value is less than the next one, subtract it; otherwise add it.
The last numeral is always added.
O(n) time and O(1) space.
Only special-casing the six subtractive pairs is fragile; the 'smaller before larger' rule covers them all.
Read the full guide first: Strings: Frequencies, Matching and Palindromes.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.