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?
num, store it as a Boolean, and then remove the sign from the string."-3-16".match(/-?\d/g).reduce(function(a,b){return +a+ +b;})