Published on

Iterate digit by given integer

Authors

Do you ever meet the question to sum all digits from the input, for example given 112 so the sum of the number is 4.

Naïve approach is to convert to string, then read character one by one. Typecast to integer, then sum all data. The simple ways to typecast rune to int using int(r - ‘0’).


_7
func Solution1(n int) int {
_7
sum := 0
_7
for _, r := range fmt.Sprintf(“%d”, n) {
_7
sum += int(r - ‘0’)
_7
}
_7
return sum
_7
}

Another way is to use an arithmetic approach by utilizing mod and division. Here are the example codes:


_9
func Solution2(n int) int {
_9
sum := 0
_9
for n > 0 {
_9
digit := n % 10
_9
sum += digit
_9
n /= 10
_9
}
_9
return sum
_9
}

So which one to use? Let's see the benchmark result first.


_10
go test -bench=Sum -benchmem -shuffle=on
_10
-test.shuffle 1673764987422236824
_10
goos: linux
_10
goarch: amd64
_10
pkg: github.com/h4ckm03d/golang-playground/6-practical-benchmark
_10
cpu: AMD Ryzen 7 5800H with Radeon Graphics
_10
BenchmarkSolution2-4 241413471 5.342 ns/op 0 B/op 0 allocs/op
_10
BenchmarkSolution1-4 14215688 84.96 ns/op 16 B/op 1 allocs/op
_10
PASS
_10
ok github.com/h4ckm03d/golang-playground/6-practical-benchmark 3.091s

The result of the benchmark Solution2 outclass Solution1 and even 0 allocation. If you encounter the similar problem to do any logic with digit from given integer, you can use the Solution2 approach to avoid time limit platform.