最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding Negative Numbers in JS - Stack Overflow

programmeradmin1浏览0评论

I am creating a function that adds up all of the digits provided within the function. So if the input is 1148 = 1 + 1 + 4 + 8 = 14

However, I am stuck if the number is negative which should count the first digit should as negative. eg. -316 = -3 + 1 + 6 = 4

What I did is that I tried to split and convert the numbers to string and to numbers again to add them up. However, for some reason this won't add the negative numbers instead it will return NaN.

function addNumbers(num) {
  var strNum = num.toString();
  strNum = strNum.split('');
  
  var total = 0;
  for(var i = 0; i < strNum.length; i++){
    total += parseInt(strNum[i]);
  }
 
  return total;
  

}

var output = addNumbers(1148);
console.log(output); // --> 14

var output2 = addNumbers(-316);
console.log(output2); // --> should return 4 instead returned NaN

I am creating a function that adds up all of the digits provided within the function. So if the input is 1148 = 1 + 1 + 4 + 8 = 14

However, I am stuck if the number is negative which should count the first digit should as negative. eg. -316 = -3 + 1 + 6 = 4

What I did is that I tried to split and convert the numbers to string and to numbers again to add them up. However, for some reason this won't add the negative numbers instead it will return NaN.

function addNumbers(num) {
  var strNum = num.toString();
  strNum = strNum.split('');
  
  var total = 0;
  for(var i = 0; i < strNum.length; i++){
    total += parseInt(strNum[i]);
  }
 
  return total;
  

}

var output = addNumbers(1148);
console.log(output); // --> 14

var output2 = addNumbers(-316);
console.log(output2); // --> should return 4 instead returned NaN

Is there a way I could fix this and take some negative to add them up?

Share Improve this question edited Sep 2, 2017 at 3:21 Dij 9,8184 gold badges20 silver badges35 bronze badges asked Sep 2, 2017 at 3:15 user8492975user8492975 4
  • Looks like a homework assignment. – harley.333 Commented Sep 2, 2017 at 3:19
  • 2 Possible duplicate of Split negative number apart and then sum together – Phani Kumar M Commented Sep 2, 2017 at 3:21
  • Perhaps the negative sign is being split by itself, and parsing it for a value returns NaN. Try checking the sign of num, store it as a Boolean, and then remove the sign from the string. – ContinuousLoad Commented Sep 2, 2017 at 3:24
  • "-3-16".match(/-?\d/g).reduce(function(a,b){return +a+ +b;}) – CrayonViolent Commented Sep 2, 2017 at 3:37
Add a ment  | 

6 Answers 6

Reset to default 1

function addNumbers(num) {
  var isNeg = num < 0,    negative
      numbers = (isNeg? String(num).slice(1) : String(num)).split('').map(Number);
  if (isNeg) numbers[0] *= -1;   
  return numbers.reduce(function(a,b){ return a + b; });
}


var output = addNumbers(1148);
console.log(output); // --> 14

var output2 = addNumbers(-316);
console.log(output2);

you are adding char '-' with numbers so you get NaN. In second case the array strNum contains '-' as first element and you add it to numbers. you can do something like this:

function addNumbers(num) {
  var strNum = num.toString();
  strNum = strNum.substr(strNum.indexOf('-')+1).split(''); //split the string after the indexof '-'.

  var total = num < 0 ? -strNum[0] : +strNum[0]; //initialize total as positive of first char or negative by checking num<0.
  for(var i = 1; i < strNum.length; i++){ //start iteration from second element in array.
     total += parseInt(strNum[i]);
  }

  return total;


}

var output = addNumbers(1148);
console.log(output); // --> 14

var output2 = addNumbers(-316);
console.log(output2); // --> should return 4 instead returned NaN

My ment was confusing, so here is some actual code :)

The idea is that the negative sign is being parsed for a number, which returns NaN.

function addNumbers(num) {
  // remove negative sign so it doesn't get parsed by itself
  var numStr = num.toString().split('').replace("-","");

  // add negative sign back if needed 
  if (num  < 0) numStr[0] = "-" + numStr[0];

// rest of function
}

Hope this helps!

function addNumbers(num) {
  var x = [],
    sum = 0;
  if (num < 0) {
    x = num.toString().split('');
    x[0] = -0;
    x[1] = x[1] * (-1);
    sum = x.reduce(function(a, b) {
      return +a + +b;
    })
  } else {
    x = num.toString().split('');
    sum = x.reduce(function(a, b) {
      return +a + +b;
    })
  }
  return sum
}
var output = addNumbers(1148);
console.log(output); // --> 14

var output2 = addNumbers(-316);
console.log(output2);

For a simpler alternative to the solutions already mentioned, you could use String#match instead of split as well as a regular expression to capture negative and positive integers : /(-?\d)/g. This will return an array that looks like ["-3", "1", "6"] when the input is -316. Nothing in the rest of your code needs to change.

function addNumbers(num) {
  var strNum = num.toString();
  strNum = strNum.match(/(-?\d)/g);
  
  var total = 0;
  for(var i = 0; i < strNum.length; i++){
    total += parseInt(strNum[i]);
  }
  return total;
}

var output = addNumbers(1148);
console.log(output); // --> 14

var output2 = addNumbers(-316);
console.log(output2); // --> should return 4 instead returned NaN

<html>
<head>
    <title>TODO supply a title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        function addNumbers(num) {
            num = num.split('');
            var posVal = 0;
            var negVal = 0;
            for(i = 0; i < num.length; i++){
                if (num[i] === "-") 
                { 
                    negVal = negVal + parseInt(num[i+1]);                        
                    i=i+1;                        
                } 
                else 
                { posVal = posVal + parseInt(num[i]);   }                   

              }
                var total =0 ;
                if (posVal >= negVal) 
                {     total = posVal - negVal;  }            
                else 
                {
                    total = negVal - posVal; 
                    total = '-' + total;
                }
                document.getElementById("negVal").innerHTML = negVal;
                document.getElementById("posVal").innerHTML = posVal;
                document.getElementById("total").innerHTML = total;
            }

    </script>

</head>

<body>
    Text
    <div>TODO write content</div>
    <p id="posVal">positive </p>
    <p id="negVal">negative</p>
    <p id="total">Total</p>
    <button type="button" onclick="addNumbers('-316')">Try it</button>
</body>

发布评论

评论列表(0)

  1. 暂无评论