Coding problem · Easy · Basics

Roman Numerals to Integer

Easy Algorithms & data structures

Convert a valid Roman numeral s (1 to 3999) to an integer. Symbols: I=1, V=5, X=10, L=50, C=100, D=500, M=1000.

A smaller symbol before a larger one is subtracted: IV = 4, IX = 9, XL = 40, CM = 900.

Example 1

Input: s = "III"
Output: 3

Example 2

Input: s = "LVIII"
Output: 58

Example 3

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90, IV = 4

Hints

Hint 1

Look up each symbol's value.

Hint 2

If a symbol is smaller than the next one, subtract it; otherwise add it.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(1)

Scan left to right. Add each value, except when it's smaller than the value after it, in which case subtract it. That single rule handles all six subtractive pairs.

Reference solution

function romanToInt(s) {
  const v = { 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 cur = v[s[i]], next = v[s[i + 1]] ?? 0;
    total += cur < next ? -cur : cur;
  }
  return total;
}

Was this page helpful?