Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda