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

121
Visualizações
convert roman numerals using for loop

I can't seem to find what am I missing? if I try 3 it will return II instead of III same thing if it's 8 it will return VII instead of VIII. I just added the 8 and 3 in my numerals variable

    VIII: 8,
    V: 5,
    IV: 4,
    III: 3,
    I: 1,

but if you guys have any suggestion to fix it without adding it in the numerals that would be great

function convertToRoman(num) {
  //values of the numbers
  let numerals = {
    M: 1000,
    CM: 900,
    D: 500,
    CD: 400,
    C: 100,
    XC: 90,
    L: 50,
    XL: 40,
    X: 10,
    IX: 9,
    V: 5,
    IV: 4,
    I: 1,
  };
  //passing the new values of the new numbers to convert into numerals
  let newNumeral = "";
  //checking the values of numerals objects
  for (let i in numerals) {
    //using the j variable of num, if the num is still greater than the numerals index it will increment the key to the variable newNumerals and stop the loop, it will subtract the num to the values of numerals .
    for (let j= 0; j <= num; j++ ){
      if(num >= numerals[i]) {
        newNumeral += i;
        num -= numerals[i];
       
      }  
    }
  }
  //return to newNumerals to see the new value.
 return newNumeral;
}

console.log(convertToRoman(3));
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The second for loop is a bit weird, you don't use j for anything.

You can replace that and the if inside with a simpler while loop.

//values of the numbers
  let numerals = {
    M: 1000,
    CM: 900,
    D: 500,
    CD: 400,
    C: 100,
    XC: 90,
    L: 50,
    XL: 40,
    X: 10,
    IX: 9,
    V: 5,
    IV: 4,
    I: 1,
  };

const convertToRoman = (num) => {
  let newNumeral = "";

  for (let i in numerals) {
    while (num >= numerals[i]) {
      newNumeral += i;
      num -= numerals[i];
    }  
  }

  return newNumeral;
}

console.log(convertToRoman(3));
console.log(convertToRoman(1990));

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