Problem
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
Ican be placed beforeV(5) andX(10) to make 4 and 9.Xcan be placed beforeL(50) andC(100) to make 40 and 90.Ccan be placed beforeD(500) andM(1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
Example:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Intuition
Roman numerals use specific rules:
- If a smaller numeral comes before a larger one, it is subtracted (e.g.,
IV = 4). - Otherwise, the values are added (e.g.,
VI = 6).
We can traverse the string, compare each numeral with the next, and decide whether to add or subtract.
Approach
- Create a helper function to map Roman numerals (
I,V,X, etc.) to their integer values. - Initialize a variable
resultto store the final integer value. - Loop through the string:
- If the current numeral is smaller than the next numeral, subtract its value from
result. - Otherwise, add its value to
result.
- If the current numeral is smaller than the next numeral, subtract its value from
- Return the final
result.
Complexity
- Time Complexity:
O(n)
The string is traversed once, wherenis its length. - Space Complexity:
O(1)
Only a few variables are used; no additional data structures.
Code
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
const romanToInt = {
'I': 1, 'V': 5, 'X': 10, 'L': 50,
'C': 100, 'D': 500, 'M': 1000
};
let result = 0;
for (let i = 0; i < s.length; i++) {
if (i + 1 < s.length && romanToInt[s[i]] < romanToInt[s[i + 1]]) {
result -= romanToInt[s[i]];
} else {
result += romanToInt[s[i]];
}
}
return result;
};

