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 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: