Sum of Digits in Go: A Simple Algorithm Tutorial

Search for a command to run...

No comments yet. Be the first to comment.
Quick, digestible posts where I tackle DSA problems using Go — perfect for developers who want to sharpen their skills with real examples.
Hello, Go enthusiast! Today we're covering a new algorithm in Go. This is a commonly asked question for entry-level positions as it covers Go basics like maps, runes, and string manipulation. We'll explore how to determine if all characters in a stri...
Building a Personal Finance API with NestJS, Supabase & Drizzle (From Zero to Production)

Building a Personal Finance API with NestJS, Supabase & Drizzle (From Zero to Production)

Building a Personal Finance API with NestJS, Supabase & Drizzle (From Zero to Production)

Building a Personal Finance API with NestJS, Supabase & Drizzle (From Zero to Production)

The Fibonacci sequence is one of the most common problems you'll solve throughout your software career. Its implementation can be as simple or complex as you want. One of the most frequently used solutions is recursion—a core concept in computer scie...

Ruben's Blog
27 posts
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.
Given an integer, return the sum of its digits. For example, if the input is
123the output should be6(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.
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
}
Initialize a variable sum to 0 to track our running total
sum := 0
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 {}
For each iteration, add the last digit of the number to the sum variable using the modulo operator.
sum += n % 10
Then, use the division assignment operator to remove the last digit from the number.
n /= 10
Finally, return the accumulated sum.
return sum
func sumDigits(n int) int {
if n < 0 {
n = -n
}
sum := 0
for n != 0 {
sum += n % 10
n /= 10
}
return sum
}
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