Explanation
The trick is IV is 4 because , I which is 1 is less than V which is 5
so we check in the iteration , that if next number is greater than current , then we need to take difference , else we can just add the value of Roman symbol
Javascript Code
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function (s) {
const RomanToIntmap = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
let res = 0;
for (let i = 0; i < s.length; i++) {
let curr = RomanToIntmap[s[i]];
let next = RomanToIntmap[s[i + 1]];
if (next > curr && next !== undefined) {
res += next - curr;
i++;
}
else {
res += curr;
}
}
return res
};
Top comments (0)