I was on leetcode and I found a problem that I wanted to solve using for in instead of if about transforming a roman number to a natural number:
let s = "IV"
let res = 0
let dic = {
M: 1000,
D: 500,
C: 100,
L: 50,
X: 10,
V: 5,
I: 1
}
after setting the basic variables i made the actual code:
for (let i in s) {
if (dic[s[i]] < dic[s[i + 1]]) {
res -= dic[s[i]];
} else {
res += dic[s[i]];
}
}
doing this the result it's 6 instead of 4 which i get surprised, if we take i = 0, we have that if (1 < 5) {res -= 1} then when i = 1 will add 5 to -1 so the result should be 4.
after trying I found a way that did it exactly as I did but using for (let i = 0; i < s.length; i++) and that worked.
My question is why does it work with another type of for? Is there a way to do it with for in as it is more readable?
i is a string. So use parseInt on it like so:
let s = "IV"
let res = 0
let dic = {
M: 1000,
D: 500,
C: 100,
L: 50,
X: 10,
V: 5,
I: 1
}
for (let i in s.split("")) {
if (dic[s[i]] < (dic[s[parseInt(i)+1]])) {
res -= dic[s[i]];
} else {
res += dic[s[i]];
}
}
console.log("res",res);