Java Program to Find Sum of Digits
num % 10, add it to a sum, and reduce the number by num = num / 10 until it becomes zero.Examples
How to Think About It
% with 10. Add this digit to a total sum. Then remove the last digit by dividing the number by 10. Repeat until the number is zero.Algorithm
Code
public class SumOfDigits { public static void main(String[] args) { int num = 123; int sum = 0; while (num > 0) { sum += num % 10; num /= 10; } System.out.println("Sum of digits: " + sum); } }
Dry Run
Let's trace the number 123 through the code to find the sum of its digits.
Start
num = 123, sum = 0
First loop
sum = 0 + 123 % 10 = 3, num = 123 / 10 = 12
Second loop
sum = 3 + 12 % 10 = 3 + 2 = 5, num = 12 / 10 = 1
Third loop
sum = 5 + 1 % 10 = 5 + 1 = 6, num = 1 / 10 = 0
End loop
num is 0, stop loop
| num | num % 10 | sum | num after division |
|---|---|---|---|
| 123 | 3 | 3 | 12 |
| 12 | 2 | 5 | 1 |
| 1 | 1 | 6 | 0 |
Why This Works
Step 1: Extract last digit
Using num % 10 gives the last digit of the number.
Step 2: Add digit to sum
Add the extracted digit to the running total sum.
Step 3: Remove last digit
Divide the number by 10 using num /= 10 to remove the last digit.
Step 4: Repeat until done
Continue until the number becomes zero, meaning all digits are processed.
Alternative Approaches
public class SumOfDigits { public static int sumDigits(int num) { if (num == 0) return 0; return num % 10 + sumDigits(num / 10); } public static void main(String[] args) { int num = 123; System.out.println("Sum of digits: " + sumDigits(num)); } }
public class SumOfDigits { public static void main(String[] args) { int num = 123; String str = Integer.toString(num); int sum = 0; for (char c : str.toCharArray()) { sum += c - '0'; } System.out.println("Sum of digits: " + sum); } }
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit in the number, so time is proportional to the number of digits, O(d).
Space Complexity
Only a few variables are used, so space is constant, O(1).
Which Approach is Fastest?
The iterative method is fastest and uses least memory; recursion adds call stack overhead; string conversion is less efficient.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative (mod/div) | O(d) | O(1) | Fastest and simplest |
| Recursive | O(d) | O(d) | Elegant but uses stack |
| String conversion | O(d) | O(d) | Easy to read, less efficient |
num % 10 to get the last digit and num /= 10 to remove it.