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

123
Visualizações
Sum of integers in a string

Here's my code:

function sumDigits(num) {

  var string = num.toString();
  var result = 0;

  for (let i = 0; i < string.length; i++) {
    if (string[i] === '-') {
      var negative = Number(string[i + 1]) * -1
      result = result + negative
    } else {
      result = result + Number(string[i])
    }
  }
  return result;
}

console.log(sumDigits('-316'))

When I add -316 as an argument, my output is 7. Why is it not taking -3 into the equation? As an FYI, I am still new to coding, and not sure this is even the correct route to take. All input is appreciated.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Learn to debug, console.log and debugger are your friend.

function sumDigits(num) {

  var string = num.toString();
  var result = 0;
  console.log("my string:", string);

  for (let i = 0; i < string.length; i++) {
    console.log("in loop", i, string[i]);
    if (string[i] === '-') {
      var negative = Number(string[i + 1]) * -1
      console.log("in if ", result, "+", negative);
      result = result + negative
      console.log("updated result", result);
    } else {
      console.log("in else ", result, "+", Number(string[i]));
      result = result + Number(string[i])
      console.log("updated result", result);      
    }
  }
  console.log("final result", result);
  return result;

}

sumDigits(-317);

Looking at the results you can see you find a negative and you get the next number. On the next iteration you read that same number again. So -3 + 3 is zero. So you cancel it out. You need to skip your loop ahead by one.

function sumDigits(num) {

  var string = num.toString();
  var result = 0;
  for (let i = 0; i < string.length; i++) {
    if (string[i] === '-') {
      var negative = Number(string[i + 1]) * -1
      result = result + negative
      // bump i
      i++;
    } else {
      result = result + Number(string[i])
    }
  }
  return result;

}

console.log(sumDigits(-317));

about 4 years ago · Juan Pablo Isaza Relatório

0

  • I am checking whether the number is greater than 0 or less than zero.
  • Then if the number is less than zero, then I am merging the first element of array which will be (-digit) digits[0] = digits[0] + digits[1];. -then I am removing 2nd element from digits array. digits.splice(1, 1);
  • And At the end I am lopping through all the digits using forEach loop and returning total of the dum digits to total.

const digitsSum = (number) => {

  let total = 0;
  if (number < 0) {
    let digits = number.toString().split('');
    digits[0] = digits[0] + digits[1];
    digits.splice(1, 1);
    digits.forEach(digit => total += parseInt(digit));
    console.log(total);
    return total;
  } else {
    let digits = number.toString().split('');
    digits.forEach(digit => total += parseInt(digit));
    console.log(total);
    return total;
  }
}

function calculateDigitSumLogic(number) {

}
digitsSum(-1203);
digitsSum(1203);
digitsSum(-201);

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