I am trying to solve this problem Roman to integer problem in LeetCode by using JavaScript. The code I got so far did not pass all tests. it is working only in some of the cases. for example, it passes test for "III" and it returns back 3, but for case where the string is "LVIII", it returns only 57 instead of 58. Also in case where string is "MCMXCIV", it returns back 1990 instead of 1994. It seems that the for loop stopped too early for some reason. Can someone please have a look at it and please let me know where I got it wrong, thanks.
var romanToInt = function(s) {
var strArr = s.split('');
var numArr = [];
var int = 0;
for(var i=0; i<strArr.length; i++) {
if(strArr[i] === 'I'){
numArr.push(1)
} else if(strArr[i] === 'V') {
numArr.push(5)
}else if(strArr[i] === 'X') {
numArr.push(10)
}else if(strArr[i] === 'L') {
numArr.push(50)
}else if(strArr[i] === 'C') {
numArr.push(100)
}else if(strArr[i] === 'D') {
numArr.push(500)
}else if(strArr[i] === 'M') {
numArr.push(1000)
}
}
for(var i=0; i<=numArr.length; i++) {
if(numArr[0] === 1000) {
int += 1000;
numArr.shift();
} else if(numArr[0] >= numArr[1]) {
int += (numArr[0] + numArr[1]);
numArr.splice(0, 2);
} else if(numArr[0] < numArr[1]){
int += (numArr[1] - numArr[0]);
numArr.splice(0, 2);
} else {
int += numArr[0]
}
}
return int;
};
console.log(romanToInt("III"), "should be 3");
console.log(romanToInt("LVIII"), "should be 58");
console.log(romanToInt("MCMXCIV"), "should be 1994");