13. Roman to Integer

Given a roman numeral, convert it to an integer.

Example:

III => 3

LVIII => 58


Solution

// When we loop through the string, we check 
// if current character has smaller value than the next character => It is subtractive form => Subtract the value from result
// Else we will add the value into result
function romanToInt(s: string): number {
const map = new Map([
['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 (map.get(s[i]) < map.get(s[i + 1])) {
result -= map.get(s[i]);
continue;
}

result += map.get(s[i]);
}

return result;
}