This question already has an answer here:
I have an array of integers:
nums := []int{1, 2, 3}
How could I make integer 123 out of that?
</div>
I appreciate @KelvinS' approach, there already exists a math.Pow
(though it deals in float64s. Never-the-less, his approach breaks down what you are really after, which is raising each successive number (from the right) by an order of magnitude and summing the numbers. As such, the most straight forward approach I can think of is
func sliceToInt(s []int) int {
res := 0
op := 1
for i := len(s) - 1; i >= 0; i-- {
res += s[i] * op
op *= 10
}
return res
}
func main() {
nums := []int{1, 2, 3}
fmt.Println(sliceToInt(nums))
}
sliceToInt
is poorly named, but you should get the idea.
https://play.golang.org/p/JS96Nq_so-
It may be a micro optimization to try to get this as fast as possible, but if it happens to be in a hot path it might be worth it
BenchmarkPow-8 100000000 13.5 ns/op 0 B/op 0 allocs/op
BenchmarkJoin-8 5000000 272 ns/op 8 B/op 5 allocs/op
BenchmarkBuffer-8 2000000 782 ns/op 160 B/op 8 allocs/op
BenchmarkSliceToInt-8 200000000 8.65 ns/op 0 B/op 0 allocs/op
PASS
Iterate over your slice and add each item to a buffer:
var buf bytes.Buffer
nums := []int{1, 2, 3}
for i := range nums {
buf.WriteString(fmt.Sprintf("%d", nums[i]))
}
You can then convert it into an integer using the strconv package.
i, err := strconv.Atoi(buf.String())
GoPlay here:
https://play.golang.org/p/8w-gc2S2xR
Try something like this:
package main
import (
"strconv"
"log"
)
func join(nums []int) (int, error) {
var str string
for i := range nums {
str += strconv.Itoa(nums[i])
}
num, err := strconv.Atoi(str)
if err != nil {
return 0, err
} else {
return num, nil
}
}
func main() {
nums := []int{1, 2, 3}
num, err := join(nums)
if err != nil {
log.Println(err)
} else {
log.Println(num)
}
}
Maybe there is a better way to do this, but this example works.
You can also iterate over the slice and build the int with arithmetic
package main
import (
"fmt"
)
func Pow(a, b int) int {
result := 1
for i := 0; i < b; i++ {
result *= a
}
return result
}
func main() {
nums := []int{1, 2, 3}
num := 0
length := len(nums)
for i, d := range nums {
num += d * Pow(10, length-i-1)
}
fmt.Println(num)
}
To me the simplest approach is:
1) Convert slice of ints to slice of strings
2) Join the strings
3) Convert resulting string into an int
package main
import (
"fmt"
"strconv"
"strings"
)
func sliceToInt(ints []int) int {
stringVals := make([]string, len(ints))
for ind, val := range ints {
stringVals[ind] = strconv.Itoa(val)
}
newInt, _ := strconv.Atoi(strings.Join(stringVals, ""))
return newInt
}
func main() {
s1 := []int{1, 2, 3}
fmt.Println(sliceToInt(s1))
s2 := []int{1, 20, 3}
fmt.Println(sliceToInt(s2))
}
Result:
123
1203
Converting slice of ints to strings, and then joining is O(N), as opposed to incrementally building out the final string, which is O(N * N).