Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
for in doesn't substract but for does

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!