Home > database >  Sum of integers in a string
Sum of integers in a string

Time:07-12

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.

CodePudding user response:

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));

CodePudding user response:

  • 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);

  • Related