Return Sum Of A Number (positive Or Negative)
I need to make a function that takes a number and returns sum of it's digits, if the number is negative the first digit should be considered negative when adding numbers, this is w
Solution 1:
Use optimized and short version of sumDigits()
function:
functionsumDigits(num) {
var isNeg = num < 0, // check whether the number is negative
numbers = (isNeg? String(num).slice(1) : String(num)).split('').map(Number);
if (isNeg) numbers[0] *= -1; // 'recovering' the number's signreturn numbers.reduce(function(a,b){ return a + b; });
}
console.log(sumDigits(1234));
console.log(sumDigits(-951));
Solution 2:
In case of negative number, the first char is '-' the minus symbol. When you are trying to convert it to number, you are getting NaN
. After that if you try to add NaN
to any number the result would be NaN
.
As a resolution, you need to ignore the first digit if the number is negative.
So, you can make a code change like
if(z === 1){
others = others - arrx[z];
}else{
others += arrx[z];
}
and also changing the return in case of negative numbers to return others;
Following code should work.
var arrx = [];
var oper;
var others = 0;
functionsumDigits(num) {
// your code herevar y = num.toString();
var c = y.split("");
c.forEach((h) => arrx.push(Number(h)) );
if (num < 0){
for (var z = 1; z < arrx.length; z++){
if(z === 1){
others = others - arrx[z];
}else{
others += arrx[z];
}
}
return others;
}
return arrx.reduce((a,b) => a+b);
}
console.log(sumDigits(-1234));
Post a Comment for "Return Sum Of A Number (positive Or Negative)"