Reputation: 75
Total golang (and programming) noob!
Given any six digit number, how could one output a slice where each character of that number is assigned an individual location within the slice?
For instance, a slice (let's call it s) containing all of these characters, would have s[0]=first digit, s[1]=second digit, s[2]=third digit and so on.
Any help would be greatly appreciated!
Upvotes: 4
Views: 15234
Reputation: 1
For this problem you can convert your int value to string and after that you can use split function which is under strings library.I hope below code will work for you!
package main
import (
"fmt"
"strings"
"strconv"
)
func main() {
num:=10101
a:=strconv.Itoa(num)
res:=strings.Split(a,"")
fmt.Println("The value of res is",res)
fmt.Printf("The type of res is %T\n",res)
fmt.Println(res[0])
}
Output: The value of res is [1 0 1 0 1] The type of res is []string 1
Upvotes: 0
Reputation: 417
I'm confused why nobody mentioned this way: (No need recursion)
import (
"fmt"
"strconv"
)
func main() {
n := 3456
fmt.Println(NumToArray(n))
fmt.Println(NumToArray2(n))
}
func NumToArray(num int) []int {
arr := make([]int, len(strconv.Itoa(num)))
for i := len(arr) - 1; num > 0; i-- {
arr[i] = num % 10
num = int(num / 10)
}
fmt.Println(arr)
return arr
}
// Without converting to string
func NumToArray2(num int) (arr []int) {
for num > 0 {
arr = append(arr, num%10)
num = int(num / 10)
}
// Reverse array to the rigtht order
for i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 {
arr[i], arr[j] = arr[j], arr[i]
}
fmt.Println(arr)
return arr
}
P.S. Benchmarks are welcome
Upvotes: 0
Reputation: 61
The above answers are correct. Here comes another version of MBB's answer. Avoiding recursion and efficient reverting may increase performance and reduce RAM consumption.
package main
import (
"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
Upvotes: 4
Reputation: 71
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
}
Upvotes: 7
Reputation: 48086
This is a two step process, first converting int to string, then iterating the string or converting to a slice. Because the built in range function lets you iterate each character in a string, I recommend keeping it as a string. Something like this;
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
}
Upvotes: 1