Roman to Integer

Easy

Given a Roman numeral string, convert it to an integer. Roman numerals are represented by: I=1, V=5, X=10, L=50, C=100, D=500, M=1000. When a smaller numeral appears before a larger one, subtract it.

Examples

InputOutput
s = "III"3
s = "MCMXCIV"1994

Python Solution

def roman_to_int(s: str) -> int:
    values = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
    total = 0
    prev = 0
    for c in reversed(s):
        v = values[c]
        total += v if v >= prev else -v
        prev = v
    return total

JavaScript Solution

function romanToInt(s) {
  const values = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
  let total = 0, prev = 0;
  for (let i = s.length - 1; i >= 0; i--) {
    const v = values[s[i]];
    total += v >= prev ? v : -v;
    prev = v;
  }
  return total;
}

Step-by-Step Explanation

  1. Process from right to left. If current value < previous, subtract; else add.
  2. This handles cases like IV (4) and IX (9) correctly.

Complexity Analysis

TimeO(n)
SpaceO(1)

Tags

StringMath

Related Problems

Related Tools

All Problems