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

308
Visualizações
return a string where each digit is repeated a number of times equals to its value

I'm trying to solve a problem: Given a string made of digits [0-9], return a string where each digit is repeated a number of times equals to its value. I did the repetition of numbers, how next - I don’t know.

function explode(s) {
  for (let i=0; i < s.length; i++){
    let y = s[i].repeat(s[i]);
    
    console.log(y);
  }
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Javascript is good at coercing numbers to string and vice versa but I prefer to make clear when a numerical character is being treated as a number and when it is intended to be a string.

My snippet tests processing of numbers, string representations of numbers, strings having mixtures of number and letter characters, and letter strings.

it makes use of array.split() to for the character array, array.map() to process the characters (including parseInt to formally change the character to a number when used as the argument the string.repeat(), and array.join() to return the desired numeric string after processing:

let number = 6789;
let numberString = "12345";
let badNum = "3bad2Number";
let noNum = "justLetters";

console.log(expandNums(number));
console.log(expandNums(numberString));
console.log(expandNums(badNum));
console.log(expandNums(noNum));

function expandNums(numOrString) {
  let numString = numOrString.toString();
  let chars = numString.split('');
  let processed = chars.map(char => char.repeat(parseInt(char)));
  
return processed.join('');
} // end function expandNums

The function performs well under all use situations tested, so is unlikely to throw an error if a bad argument is passes. It also does a good job with the mixed letter/number example.

about 4 years ago · Juan Pablo Isaza Relatório

0

You were only missing a result string to collect the parts

function explode(input) {
  let result = '';
  let s = input.toString();  // So that input can also be a number
  for (let i=0; i < s.length; i++){
    let y = s[i].repeat(s[i]);
    result += y;
  }
  return result;
}
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