Question:
Write a function digitsum that calculates the digit sum of an integer. The digit sum of an integer is the sum of all its digits.
Example: digitsum(192) should return 12.
Answer:
function digitsum (n) {
let digits = n.toString().split('').map(x => x * 1);
let sum = digits.reduce((acc,cv) => acc + cv);
return sum;
};
> declare a function 'digitsum'
> it has one parameter 'n'
> we create our first variable 'digits'
> we initialize it with the output we get by converting the input 'n'
>>> from a number to a string,
>>> then splitting the string in an array format
>>> and then converting the array of strings to a number by using the map method
> we then create our final variable sum and initialize it with a value we get by using the reduce method on the variable 'digits'
> finally we return 'sum'
No comments:
Post a Comment