Kotlin Program to Find Sum of Digits of a Number
number.toString().sumOf { it.digitToInt() } or by repeatedly extracting digits with number % 10 and adding them.Examples
How to Think About It
% 10 and add it to a total, then remove that digit by dividing by 10 until the number is zero.Algorithm
Code
fun main() {
var number = 123
var sum = 0
while (number > 0) {
sum += number % 10
number /= 10
}
println(sum)
}Dry Run
Let's trace the number 123 through the code to find the sum of its digits.
Initial values
number = 123, sum = 0
First iteration
sum = 0 + 123 % 10 = 3, number = 123 / 10 = 12
Second iteration
sum = 3 + 12 % 10 = 3 + 2 = 5, number = 12 / 10 = 1
Third iteration
sum = 5 + 1 % 10 = 5 + 1 = 6, number = 1 / 10 = 0
Loop ends
number is 0, stop loop, sum = 6
| number | number % 10 | sum | number / 10 |
|---|---|---|---|
| 123 | 3 | 3 | 12 |
| 12 | 2 | 5 | 1 |
| 1 | 1 | 6 | 0 |
Why This Works
Step 1: Extract last digit
Using number % 10 gets the last digit of the number because modulo gives the remainder after division by 10.
Step 2: Add digit to sum
Add the extracted digit to the running total stored in sum.
Step 3: Remove last digit
Divide the number by 10 using integer division to remove the last digit and prepare for the next iteration.
Step 4: Repeat until done
Continue until the number becomes zero, meaning all digits have been processed.
Alternative Approaches
fun main() {
val number = 123
val sum = number.toString().sumOf { it.digitToInt() }
println(sum)
}fun sumDigits(n: Int): Int = if (n == 0) 0 else n % 10 + sumDigits(n / 10) fun main() { println(sumDigits(123)) }
Complexity: O(d) time, O(1) space
Time Complexity
The time depends on the number of digits d in the number because each digit is processed once in the loop.
Space Complexity
Only a few variables are used, so space is constant O(1).
Which Approach is Fastest?
The loop with modulo and division is fastest and uses less memory than string conversion or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Modulo and division loop | O(d) | O(1) | Efficient for all number sizes |
| String conversion and sumOf | O(d) | O(d) | Simple code, good for small to medium numbers |
| Recursive approach | O(d) | O(d) | Elegant but risky for large numbers due to stack use |
number % 10 to get the last digit and number / 10 to remove it when summing digits.