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条)

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误