This question already has an answer here:
- One-liner to transform []int into string 4 answers
I have an array of integers:
nums := []int{1, 2, 3}
How could I make integer 123 out of that?
</div>
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