Published on

# Iterate digit by given integer

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

`_7func 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:

`_9func 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.

`_10go test -bench=Sum -benchmem -shuffle=on _10-test.shuffle 1673764987422236824_10goos: linux_10goarch: amd64_10pkg: github.com/h4ckm03d/golang-playground/6-practical-benchmark_10cpu: AMD Ryzen 7 5800H with Radeon Graphics _10BenchmarkSolution2-4 241413471 5.342 ns/op 0 B/op 0 allocs/op_10BenchmarkSolution1-4 14215688 84.96 ns/op 16 B/op 1 allocs/op_10PASS_10ok 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.