How to useMath.floor and Division in Javascript
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.
function sumOfDigits(num) {
let sum = 0;
for (; num > 0; num = Math.floor(num / 10)) {
sum += num % 10;
}
return sum;
}
console.log(sumOfDigits(456));
Output
15
JavaScript Program for Sum of Digits of a Number
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:
Table of Content
- Approach 1: Using Array Reduce() Method
- Approach 2: Using For…of Loop
- Approach 3: Using Math.floor and Division
- Approach 4: Using forEach
- Approach 5: Using Recursion
We will explore all the above methods along with their basic implementation with the help of examples.