Files
JavaScript/Maths/SumOfDigits.js
Legendary Noob b3b4ad43a3 chore: Added Sum of Digits Implementation (#684)
* Added the main logic, need to work on Tests

* Added tests for SOD

* Fix typo and add Wikipedia link in comments

* Fix mistake in SumOfDigitsUsingStrings

I intended to initially write a different implementation but I wrote something else 🤦‍♂️

* Converted Spacing from Tabs to Spaces

* Oops, forgot about the test file

* Fixed semicolon problems...

* Oops, I missed a few semicolons

* Linting is hell TwT

Co-authored-by: SpiderMath <{ID}+{username}@users.noreply.github.com>
2021-09-13 19:41:28 +05:30

47 lines
1.6 KiB
JavaScript

/*
Gets the sum of the digits of the numbers inputted
sumOfDigits(10) will return 1 + 0 = 1
sumOfDigits(255) will return 2 + 5 + 5 = 12
Wikipedia: https://en.wikipedia.org/wiki/Digit_sum
*/
/*
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
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) {
if (number < 0) number = -number
return Number.parseInt(number.toString().split('').reduce((a, b) => Number(a) + Number(b)))
}
/*
The input is divided by 10 in each iteraction, till the input is equal to 0
The sum of all the digits is returned (The res variable acts as a collector, taking the remainders on each iteration)
*/
function sumOfDigitsUsingLoop (number) {
if (number < 0) number = -number
let res = 0
while (number > 0) {
res += number % 10
number = Math.floor(number / 10)
}
return res
}
/*
We use the fact that the sum of the digits of a one digit number is itself, and check whether the number is less than 10. If so, then we return the number. Else, we take the number divided by 10 and floored, and recursively call the function, while adding it with the number mod 10
*/
function sumOfDigitsUsingRecursion (number) {
if (number < 0) number = -number
if (number < 10) return number
return (number % 10) + sumOfDigitsUsingRecursion(Math.floor(number / 10))
}
export { sumOfDigitsUsingRecursion, sumOfDigitsUsingLoop, sumOfDigitsUsingString }