I have two solutions to roman to integer in javascript (leetcode link), where the first one doesn't work and the second one does. The odd thing is I can't tell any difference between the two. I'm sure I'm missing something, but can't tell.
Here's the code sandbox Can't tell why romanToInt function doesn't work while romanToInt2 does.
var romanToInt = function(s) {
//create a map of roman numeral to int value equivalent
let map = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
};
let total = 0;
for (let i = 0; i < s.length; i++) {
let curR = s[i];
let nextR = s[i + 1];
let cur = map[curR];
let next = map[nextR];
if (next) {
if (cur >= next) {
total += cur;
} else {
total += next - cur;
i++;
}
} else {
total += cur;
}
return total;
}
};
console.log(romanToInt("III"), 3);
var romanToInt2 = function(s) {
const map = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
};
let total = 0;
for (let i = 0; i < s.length; i++) {
let curR = s[i];
let nextR = s[i + 1];
let cur = map[curR];
let next = map[nextR];
if (next) {
if (cur >= next) {
total += cur;
} else {
total += next - cur;
i++;
}
} else {
total += cur;
}
}
return total;
};
console.log(romanToInt2("III"), 3);
I just checked your code, and its all about the return statement.
The first function romanToInt returns the result in the for loop at the first iteration only, while the second function, romanToInt2 the return is outside of for loop, which means the for loop is executed and then the result is returned,
A little hack, when in doubt of two functions exactly same, use any diff checker and paste the code to check the diff. It's easy to tell the difference when visualised. I just put your two functions here, and it was quick.