Roman numeral to integer

Easy TimeO(n) SpaceO(1)

Roman numerals are read by adding their symbols left to right — I 1, V 5, X 10, L 50, C 100, D 500, M 1000 — except that a smaller symbol placed immediately before a larger one is taken away instead, so "IV" is 4 rather than 6. Given a well-formed numeral s, return the number it stands for. Only six such pairs exist: IV, IX, XL, XC, CD and CM.

Examples

Example 1

Input
s = "MCMXCIV"
Output
1994
M 1000, CM 900, XC 90, IV 4 → 1000 + 900 + 90 + 4.

Example 2

Input
s = "LVIII"
Output
58
L 50, V 5, III 3, with nothing taken away → 50 + 5 + 3.

The Code

function romanToInt(s) {
  const value = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
  let total = 0;
  for (let i = 0; i < s.length; i++) {
    const current = value[s[i]];
    const next = value[s[i + 1]] || 0;
    if (current < next) total -= current;
    else total += current;
  }
  return total;
}
romanToInt("MCMXCIV");
Done
Step through romanToInt("MCMXCIV") call by call