13/670

13. Roman to Integer

Easy

Roman numerals use seven letters — I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000 — written from largest value to smallest, and the values add up. The exception is the subtraction rule: in six specific pairs a smaller letter stands directly before a larger one and is subtracted instead of added. IV = 4 and IX = 9, XL = 40 and XC = 90, CD = 400 and CM = 900.

You receive a string s that is a valid Roman numeral for some number between 1 and 3999. Return that number as an integer.

Example 1:

Input: s = "MCMXCIV"

Output: 1994

Explanation: M = 1000, CM = 900, XC = 90, IV = 4. Total 1994.

Example 2:

Input: s = "LVIII"

Output: 58

Explanation: L = 50, V = 5, III = 3 — purely additive, total 58.

Constraints:

  • 1 ≤ s.length ≤ 15
  • s contains only the characters I, V, X, L, C, D, M
  • s is a valid Roman numeral representing a number in [1, 3999]

Hints:

If you simply add up every letter's value, the only inputs you get wrong are the ones containing a subtractive pair — and you overshoot each pair by exactly twice the smaller letter.

One clean pass: a letter is subtracted exactly when the letter after it has a strictly larger value. Compare each character with its right neighbor and add or subtract accordingly.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: s = "MCMXCIV"

Expected output: 1994