Drill

ProblemsGo › warmup

Sum of digits

easywarmupMathGo

A checksum routine needs the digits of a number added together.

digitSum(amount: int) → int

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func digitSum(amount int) int {
	
}

Worked examples

CallResult
digitSum(0)0
digitSum(7)7
digitSum(1234)10
digitSum(-204)6

Hint

Take the absolute value first, then peel digits off with % 10 and / 10.

Reference solution in Go
func digitSum(amount int) int {
	x := amount
	if x < 0 {
		x = -x
	}
	total := 0
	for x > 0 {
		total += x % 10
		x /= 10
	}
	return total
}

The same problem in another language

More warmup problems in Go