-
慕妹3242003
func IntToSlice(n int64, sequence []int64) []int64 { if n != 0 { i := n % 10 // sequence = append(sequence, i) // reverse order output sequence = append([]int64{i}, sequence...) return IntToSlice(n/10, sequence) } return sequence}
-
慕村9548890
这是一个两步过程,首先将 int 转换为字符串,然后迭代字符串或转换为切片。因为内置的 range 函数允许您迭代字符串中的每个字符,所以我建议将其保留为字符串。像这样的东西; import "strconv" str := strconv.Itoa(123456) for i, v := range str { fmt.Println(v) //prints each char's ASCII value on a newline fmt.Printf("%c\n", v) // prints the character value }
-
慕姐8265434
以上答案都是正确的。这是MBB答案的另一个版本。避免递归和高效恢复可能会提高性能并减少 RAM 消耗。package mainimport ( "fmt")func reverseInt(s []int) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] }}func splitToDigits(n int) []int{ var ret []int for n !=0 { ret = append(ret, n % 10) n /= 10 } reverseInt(ret) return ret}func main() { for _, n := range splitToDigits(12345) { fmt.Println(n) }}https://play.golang.org/p/M3aOUnNIbdv