mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-04 15:39:42 +08:00
Update: Added Unary Operator in SumOfDigits algorithm (#1348)
* Update: Added Unary Operator in SumOfDigits algorithm * Update: Added Unary Operator in SumOfDigits algorithm
This commit is contained in:
@ -8,12 +8,11 @@
|
|||||||
/*
|
/*
|
||||||
The given input is converted to a string, split into an array of characters.
|
The given input is converted to a string, split into an array of characters.
|
||||||
This array is reduced to a number using the method <Array>.reduce
|
This array is reduced to a number using the method <Array>.reduce
|
||||||
NOTE: The final parseInt is just there in cases where 1 digit numbers are given, since without that it would result in a String output.
|
|
||||||
*/
|
*/
|
||||||
function sumOfDigitsUsingString (number) {
|
function sumOfDigitsUsingString (number) {
|
||||||
if (number < 0) number = -number
|
if (number < 0) number = -number
|
||||||
|
|
||||||
return Number.parseInt(number.toString().split('').reduce((a, b) => Number(a) + Number(b)))
|
return +(number.toString().split('').reduce((a, b) => (+a) + (+b)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
Reference in New Issue
Block a user