Leetcode – 13. Roman to Integer
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.
Solution
Idea
This is an easy problem for brute force but I want something beautiful. I managed to submit a little bit nicer brute force solution. It passed but I’m still not satisfied.
Later, I found out that 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.
Code
Brute force solution
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
let romans = {
'IV': 4,
'IX': 9,
'I': 1,
'V': 5,
'XL': 40,
'XC': 90,
'X': 10,
'L': 50,
'CD': 400,
'CM': 900,
'C': 100,
'D': 500,
'M': 1000
}
let result = 0;
let i = s.length - 1;
while (i >= 0) {
if (romans[s[i - 1] + s[i]]) {
result += romans[s[i - 1] + s[i]];
i -= 2;
} else {
result += romans[s[i]]
i--;
}
}
return result;
};
Refined version
/**
* @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;
};Yep it’s more beautiful.