Convert Roman numerals to decimal

Easy

Problem

Convert a valid Roman numeral (I=1, V=5, X=10, L=50, C=100, D=500, M=1000) to an integer. A smaller symbol placed before a larger one is subtracted: IV = 4, CM = 900.

Example 1

Input:  "MCMXCIV"
Output: 1994

M (1000) + CM (900) + XC (90) + IV (4).

Also asked as: Converting Roman Numerals to Decimal

Test cases

Case 1

Input:    "MCMXCIV"
Expected: 1994

Case 2

Input:    "LVIII"
Expected: 58

Case 3

Input:    "IX"
Expected: 9

Case 4

Input:    "III"
Expected: 3

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Subtract when a smaller value precedes a larger

Time O(n)Space O(1)

Add each symbol’s value, but if it is smaller than the next symbol, subtract it instead.

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++) {
if (i + 1 < s.length && v[s[i]] < v[s[i + 1]]) total -= v[s[i]];
else total += v[s[i]];
}
return total;
}