Go Program to Find Sum of Digits of a Number
num % 10, adding it to a sum variable, and then removing the last digit with num /= 10 until the number becomes zero.Examples
How to Think About It
%, add it to a running total, then remove that digit by dividing the number by 10. Repeat until no digits remain.Algorithm
Code
package main import "fmt" func main() { num := 12345 sum := 0 for num > 0 { digit := num % 10 sum += digit num /= 10 } fmt.Println(sum) }
Dry Run
Let's trace the number 123 through the code to find the sum of its digits.
Initial values
num = 123, sum = 0
First iteration
digit = 123 % 10 = 3, sum = 0 + 3 = 3, num = 123 / 10 = 12
Second iteration
digit = 12 % 10 = 2, sum = 3 + 2 = 5, num = 12 / 10 = 1
Third iteration
digit = 1 % 10 = 1, sum = 5 + 1 = 6, num = 1 / 10 = 0
Loop ends
num is now 0, loop stops, sum = 6
| num before | digit extracted | sum after | 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 gets the last digit of the number because it gives the remainder after dividing 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 num /= 10 to drop the last digit and move to the next.
Alternative Approaches
package main import ( "fmt" "strconv" ) func main() { num := 12345 sum := 0 strNum := strconv.Itoa(num) for _, ch := range strNum { digit := int(ch - '0') sum += digit } fmt.Println(sum) }
package main import "fmt" func sumDigits(num int) int { if num == 0 { return 0 } return num%10 + sumDigits(num/10) } func main() { fmt.Println(sumDigits(12345)) }
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit in the number, so time depends on the number of digits, which is O(d).
Space Complexity
Only a few variables are used, so space is constant O(1).
Which Approach is Fastest?
The arithmetic method using modulo and division is fastest and uses least memory compared to string conversion or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Modulo and Division | O(d) | O(1) | Fastest and simplest for numeric input |
| String Conversion | O(d) | O(d) | Easy to understand, slower for large numbers |
| Recursion | O(d) | O(d) | Clean code but uses stack memory |