JavaScript Program for Sum of Digits of a Number
Last Updated :
28 May, 2024
In this article, we are going to learn about finding the Sum of Digits of a number using JavaScript. The Sum of Digits refers to the result obtained by adding up all the individual numerical digits within a given integer. It's a basic arithmetic operation. This process is repeated until a single-digit sum, also known as the digital root.
There are several methods that can be used to find the Sum Of Digits by using JavaScript, which are listed below:
We will explore all the above methods along with their basic implementation with the help of examples.
Approach 1: Using Array Reduce() Method
In this approach, the reduce method transforms each digit of a number into an accumulated sum. It converts the number to a string, iterates, and adds each digit to the sum.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr), initialValue )
Example: In this example, the sumOfDigit function converts the number to a string, splits it into digits, and then reduces by adding parsed digits, resulting in the sum.
JavaScript
function sumOfDigit(num) {
return num.toString().split("")
.reduce((sum, digit) =>
sum + parseInt(digit), 0);
}
console.log(sumOfDigit(738));
In this approach, Iterate through each digit of a number by converting it to a string, then use a for...of loop to add parsed digits, resulting in the sum.
Syntax:
for ( variable of iterableObjectName) {
. . .
}
Example: In this example we are using the above-explained approach.
JavaScript
function sumOfDigit(num) {
let numStr = num.toString();
let sum = 0;
for (let digit of numStr) {
sum += parseInt(digit);
}
return sum;
}
console.log(sumOfDigit(738));
Approach 3: Using Math.floor and Division
In this approach, we calculate sum by repeatedly adding last digit using remainder of 10 and updating number by division, until it's 0.
Syntax:
Math.floor( value )
Example: In this example we are using above-explained approach.
JavaScript
function sumOfDigits(num) {
let sum = 0;
for (; num > 0; num = Math.floor(num / 10)) {
sum += num % 10;
}
return sum;
}
console.log(sumOfDigits(456));
Approach 4: Using forEach
In this approach, we are converting the number to a string, split it into digits, and use forEach loop to add parsed digits, obtaining the sum.
Syntax:
array.forEach(callback(element, index, arr), thisValue)
Example: In this example, the number 123 is converted to a string and then split into an array of individual digits. The forEach loop iterates through each digit in the array. Inside the loop, each digit is parsed and added to the sum variable.
JavaScript
function sumOfDigit(num) {
let sum = 0;
num.toString().split("").forEach(digit => {
sum += parseInt(digit);
});
return sum;
}
console.log(sumOfDigit(123));
Approach 5: Using Recursion
In this approach, we use a recursive function to repeatedly add the last digit of the number (obtained using modulo 10) and call itself with the number divided by 10 until the number becomes 0.
Example: In this example, the recursiveSum function calls itself with the number divided by 10, adding the last digit each time, until the number becomes 0.
JavaScript
function recursiveSum(num) {
if (num === 0) {
return 0;
}
return (num % 10) + recursiveSum(Math.floor(num / 10));
}
console.log(recursiveSum(738));
Similar Reads
JavaScript Program for Sum of Digits of a Number using Recursion We are given a number as input and we have to find the sum of all the digits contained by it. We will split the digits of the number and add them together using recursion in JavaScript. Table of Content Recursively Summing DigitsUsing string manipulation with recursionRecursively Summing DigitsIn th
2 min read
JavaScript Program for Sum of Number Digits in a Linked List We are going to write a JavaScript program on how to find the sum of number digits stored in a linked list. We are going to use the Iterative and Recursive techniques to find the Sum of number digits. A linked list is a data structure where elements are stored in nodes and each node points to the ne
2 min read
JavaScript Program to Find the Sum of Digits in a Factorial Let's first define the problem before proceeding to a solution. Any positive number less than or equal to n is the product of all positive integers, and the factorial of a non-negative integer n is denoted by n!. For example, 5!, sometimes known as "five factorial," is equivalent to 5 Ã 4 Ã 3 Ã 2 Ã
3 min read
JavaScript Program to Check Whether a Number is Harshad Number A Harshad number (also called Niven number) is a number that is divisible by the sum of its digits. In other words, if you take a number, sum up its digits, and if the original number is divisible by that sum, then it's a Harshad number. For example, 18 is a Harshad number because the sum of its dig
2 min read
JavaScript Program to Add Two Binary Strings Here are the various ways to add two binary stringsUsing parseInt() and toString() The parseInt() method used here first converts the strings into the decimal. Ten of these converted decimal values are added together and by using the toString() method, we convert the sum back to the desired binary r
4 min read
PHP | Sum of digits of a number This is a simple PHP program where we need to calculate the sum of all digits of a number. Examples: Input : 711 Output : 9 Input : 14785 Output : 25 In this program, we will try to accept a number in the form of a string and then iterate through the length of the string. While iterating we will ext
1 min read
Javascript Program For Adding 1 To A Number Represented As Linked List Number is represented in linked list such that each digit corresponds to a node in linked list. Add 1 to it. For example 1999 is represented as (1-> 9-> 9 -> 9) and adding 1 to it should change it to (2->0->0->0) Below are the steps : Reverse given linked list. For example, 1->
5 min read
How to find Sum the Digits of a given Number in PHP ? We will explore how to find the sum of the digits of a given number in PHP. This task involves extracting each digit from the number and adding them together to get the final sum. Table of Content Using a loop to extract digits one by oneUsing mathematical operations to extract digitsUsing a loop to
2 min read
Sum of Digits of a Number Given a number n, find the sum of its digits.Examples : Input: n = 687Output: 21Explanation: The sum of its digits are: 6 + 8 + 7 = 21Input: n = 12Output: 3Explanation: The sum of its digits are: 1 + 2 = 3Table of Content[Approach 1] Digit Extraction - O(log10n) Time and O(1) Space[Approach 2] Using
6 min read
TCS Coding Practice Question | Sum of Digits of a number Given a number, the task is to find the Sum of Digits of this number using Command Line Arguments. Examples: Input: num = 687 Output: 21 Input: num = 12 Output: 3 Approach: Since the number is entered as Command line Argument, there is no need for a dedicated input lineExtract the input number from
4 min read