I found that this solution doesn't handle the "Invalid Roman Numeric Value".
Ex: If we pass IIXX, The output is 20 which is wrong since the IIXX is invalid roman number. In this case, we throw an error, rest of the code continues..
Here is my js solution:
function romanToInt(s) {
const d = {I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000};
let summ = 0;
const n = s.length;
let i = 0;
while (i < n) {
if(i > 1 && d[s[i - 2]] < d[s[i - 1]] && d[s[i]] <= d[s[i - 1]]) {
throw new Error(`Invalid Roman numeric sequence ${s}`);
}
if (i < n - 1 && d[s[i]] < d[s[i + 1]]) {
summ += d[s[i + 1]] - d[s[i]];
i += 2;
} else {
summ += d[s[i]];
i++;
}
}
return summ;
}
console.log(romanToInt('IIXX'));
console.log(romanToInt('MMD'));
Note
It would be helpful if you add the example test cases when you have the solution for the problem.
I found that this solution doesn't handle the "Invalid Roman Numeric Value".
Ex: If we pass
IIXX, The output is20which is wrong since theIIXXis invalid roman number. In this case, we throw an error, rest of the code continues..Here is my
jssolution:Note
It would be helpful if you add the example test cases when you have the solution for the problem.