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

210
Views
roman to integer identical functions generating different results

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

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

0

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.

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!