Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda