Digits
Converts an integer to an array of digits.
- Use
strconv.Itoa()to convert the given number to a string,make()andlen()to create an appropriate slice. - Use
rangein combination withstrings.Split()to iterate over the digits, converting them tointusingstrconv.Atoi().
import (
"strconv"
"strings"
)
func Digits(n int) []int {
s := strconv.Itoa(n)
d := make([]int, len(s))
for i, l := range strings.Split(s, "") {
d[i], _ = strconv.Atoi(l)
}
return d
}Digits(123) // [1 2 3]