DEV Community

Cover image for Sum of Digits in Go: A Simple Algorithm Tutorial
Ruben Alvarado
Ruben Alvarado

Posted on

Sum of Digits in Go: A Simple Algorithm Tutorial

Hello, Go enthusiast! We're continuing our roadmap toward landing that dream job. Today we're covering another simple algorithm to help you practice working with data types and basic looping in Go.

Join me as we solve the classic Sum Digits algorithm and land that dreamed job.

Problem Statement

Given an integer, return the sum of its digits. For example, if the input is 123 the output should be 6 (1+2+3).

Let's break down the problem statement: we have an integer as input, we need to process each of its digits, and return an integer as output.

Now that we've established our input, process, and output, let's define our algorithm to solve it.

Algorithm to Solve It

First, we need to check if our input is negative. If it is, we'll convert it to a positive value.

if n < 0 {
    n = -n
}
Enter fullscreen mode Exit fullscreen mode

Initialize a variable sum to 0 to track our running total

sum := 0
Enter fullscreen mode Exit fullscreen mode

Now, implement a loop that continues as long as n is not zero. In Go, this for loop works like a while loop, checking if n is greater than 0

for n != 0 {}
Enter fullscreen mode Exit fullscreen mode

For each iteration, add the last digit of the number to the sum variable using the modulo operator.

sum += n % 10
Enter fullscreen mode Exit fullscreen mode

Then, use the division assignment operator to remove the last digit from the number.

n /= 10
Enter fullscreen mode Exit fullscreen mode

Finally, return the accumulated sum.

return sum
Enter fullscreen mode Exit fullscreen mode

Complete Function Implementation

func sumDigits(n int) int {
    if n < 0 {
        n = -n
    }
    sum := 0
    for n != 0 {
        sum += n % 10
        n /= 10
    }
    return sum
}
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

Go is a beautiful language. This simple yet efficient function demonstrates the language's minimalist mindset. With the rapidly growing demand for Go developers, strengthening your fundamentals is essential to landing that desired job.

Remember, keep learning. Improvement is a marathon, not a sprint. As always, you can find the code for this and other examples in my GitHub repository: https://github.com/RubenOAlvarado/algorithms

Cover photo belongs to Bekky Bekks in Unsplash

Top comments (0)