JavaScript: Sum of the digits of a number
JavaScript Math: Exercise-68 with Solution
Sum of Digits
Write a JavaScript program to calculate the sum of a given number's digits.
In mathematics, the digit sum of a natural number in a given number base is the sum of all its digits. For example, the digit sum of the decimal number 6098 would be 6+0+9+8=23.
Sample Data:
6098 -> 23
-501 -> 6
2546 -> 17
Sample Solution-1:
JavaScript Code:
Output:
23 6 17
Flowchart:

Live Demo:
Sample Solution-2:
JavaScript Code:
Output:
23 6 17 1 5
Flowchart:

Live Demo:
For more Practice: Solve these Related Problems:
- Write a JavaScript function that calculates the sum of the digits of a number by converting it to a string and iterating over each character.
- Write a JavaScript function that computes the sum of digits using arithmetic operations without converting the number to a string.
- Write a JavaScript function that recursively calculates the digit sum and handles negative numbers by taking absolute values.
- Write a JavaScript function that returns both the sum of the digits and the total number of digits present.
Go to:
PREV : Sum of Geometric Progression.
NEXT : Find All Primes Below N.
Improve this sample solution and post your code through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.