dongqia0240 2017-06-23 20:38
浏览 168
已采纳

将整数数组中的数字连接成Golang中的一个数字? [重复]

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>
  • 写回答

5条回答 默认 最新

  • dongyu3712 2017-06-23 21:55
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?