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
Destructively Sum all the digits of a number in JavaScript
Our main task is to write a function that destructively sums all the digits of a number using JavaScript. This approach modifies the original number during the calculation process by extracting each digit until none remain.
Understanding the Problem
The goal is to create a function that calculates the sum of all digits in a given number. The term "destructive" means the original number is modified during the process as we extract each digit.
For example, given the number 123, we need to calculate: 1 + 2 + 3 = 6.
Algorithm
Step 1 ? Create a function named getDigitSum that accepts a number parameter.
Step 2 ? Initialize a variable sum to store the cumulative total.
Step 3 ? Use a while loop that continues as long as the number is greater than zero.
Step 4 ? Extract the rightmost digit using modulus operator (%) and add it to sum.
Step 5 ? Remove the rightmost digit by dividing by 10 and using Math.floor().
Step 6 ? Return the final sum when all digits are processed.
Implementation
// Function to calculate the sum of all digits destructively
function getDigitSum(num) {
let sum = 0;
while (num > 0) {
// Extract rightmost digit and add to sum
sum += num % 10;
// Remove rightmost digit
num = Math.floor(num / 10);
console.log(`Current sum: ${sum}, Remaining number: ${num}`);
}
return sum;
}
// Test with different numbers
console.log("=== Example 1: 123456 ===");
const result1 = getDigitSum(123456);
console.log(`Final sum: ${result1}`);
console.log("<br>=== Example 2: 9876 ===");
const result2 = getDigitSum(9876);
console.log(`Final sum: ${result2}`);
=== Example 1: 123456 === Current sum: 6, Remaining number: 12345 Current sum: 11, Remaining number: 1234 Current sum: 15, Remaining number: 123 Current sum: 17, Remaining number: 12 Current sum: 19, Remaining number: 1 Current sum: 20, Remaining number: 0 Final sum: 20 === Example 2: 9876 === Current sum: 6, Remaining number: 987 Current sum: 13, Remaining number: 98 Current sum: 21, Remaining number: 9 Current sum: 30, Remaining number: 0 Final sum: 30
How It Works
The function uses two key operations in each iteration:
-
num % 10- Extracts the rightmost digit -
Math.floor(num / 10)- Removes the rightmost digit
This process continues until the number becomes 0, meaning all digits have been extracted and summed.
Alternative Approach
// Non-destructive approach using string conversion
function getDigitSumNonDestructive(num) {
return num.toString()
.split('')
.map(digit => parseInt(digit))
.reduce((sum, digit) => sum + digit, 0);
}
console.log("Destructive approach:", getDigitSum(12345));
console.log("Non-destructive approach:", getDigitSumNonDestructive(12345));
Destructive approach: 15 Non-destructive approach: 15
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Destructive (while loop) | O(log n) | O(1) |
| Non-destructive (string) | O(log n) | O(log n) |
The destructive approach has better space efficiency as it uses constant extra space, while the time complexity depends on the number of digits in the input.
Conclusion
The destructive digit sum function provides an efficient solution with O(log n) time and O(1) space complexity. While the original number is modified during processing, this approach is memory-efficient for large numbers.
