Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Recursive sum all the digits of a number JavaScript
Let's say, we are required to create a function that takes in a number and finds the sum of its digits recursively until the sum is a one-digit number.
For example ?
findSum(12345) = 1+2+3+4+5 = 15 = 1+5 = 6
So, the output should be 6.
How Recursive Digit Sum Works
The process involves two levels of recursion:
- Extract and sum individual digits of a number
- Repeat the process until we get a single digit
Method 1: Using Mathematical Operations
Let's write the code for this function findSum() ?
// using recursion
const findSum = (num) => {
if(num < 10){
return num;
}
const lastDigit = num % 10;
const remainingNum = Math.floor(num / 10);
return findSum(lastDigit + findSum(remainingNum));
}
console.log(findSum(2568));
console.log(findSum(12345));
console.log(findSum(999));
3 6 9
Method 2: Using String Conversion
An alternative approach converts the number to a string to easily access individual digits:
const findSumString = (num) => {
if(num < 10) {
return num;
}
let sum = 0;
const numStr = num.toString();
for(let digit of numStr) {
sum += parseInt(digit);
}
return findSumString(sum);
}
console.log(findSumString(2568));
console.log(findSumString(87654));
console.log(findSumString(1));
3 3 1
How It Works
The first method works by:
- Checking if the number is less than 10 (base case)
- Extracting the last digit using modulo operator (%)
- Getting remaining digits using Math.floor() and division
- Recursively calling the function on both parts
Step-by-Step Example
For findSum(2568):
2568 ? 2+5+6+8 = 21 21 ? 2+1 = 3 3 < 10, so return 3
Comparison
| Method | Approach | Readability | Performance |
|---|---|---|---|
| Mathematical | Modulo and division | Complex | Faster |
| String conversion | String iteration | Simple | Slower |
Conclusion
Recursive digit sum reduces any number to a single digit by repeatedly summing its digits. The mathematical approach is more efficient, while string conversion is easier to understand.
Advertisements
