Iterate digit by given integer

# Iterate digit by given integer

January 15, 2023 Name
Moch Lutfi
@kaptenupi

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’)`.

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

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

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

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

`go test -bench=Sum -benchmem -shuffle=on -test.shuffle 1673764987422236824goos: linuxgoarch: amd64pkg: github.com/h4ckm03d/golang-playground/6-practical-benchmarkcpu: AMD Ryzen 7 5800H with Radeon Graphics BenchmarkSolution2-4 241413471 5.342 ns/op 0 B/op 0 allocs/opBenchmarkSolution1-4 14215688 84.96 ns/op 16 B/op 1 allocs/opPASSok 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.