13. Find the Sum of Digits of a Number
Given an integer, calculate the sum of all its digits.
How It Works & Algorithmic Design
Use modulo and integer division:
- Convert the number to its absolute value.
- Extract the last digit using
n % 10. - Add the digit to
sum. - Remove the last digit using integer division by
10. - Continue until the number becomes
0.
Why This Approach Works Best
Each digit is processed exactly once, resulting in $O(d)$ time where $d$ is the number of digits and $O(1)$ space.
Example Walkthrough
Input
583
The number contains digits 5, 8, and 3.
Calculation
3 + 8 + 5 = 16
Digits are extracted from right to left.
Output
16
The sum of all digits is 16.
Answer: Sum digits
function sumDigits(n) {
n = Math.abs(n);
let sum = 0;
while (n > 0) {
sum += n % 10;
n = Math.floor(n / 10);
}
return sum;
}Extract each digit using modulo 10 and remove it using integer division.
Key Takeaways
The modulo operator extracts the last digit.
Integer division removes the processed digit.
Each digit is visited once, giving O(d) time.