将整数数组中的数字连接成一个数字,在Golang中如何实现?

huangapple go评论81阅读模式
英文:

Join digits from integer array into one number in Golang?

问题

我有一个整数数组:

nums := []int{1, 2, 3}

我如何将这个数组中的整数组合成数字123?

英文:

I have an array of integers:

nums := []int{1, 2, 3}

How could I make integer 123 out of that?

答案1

得分: 6

我欣赏@KelvinS的方法,已经存在一个math.Pow函数(尽管它处理的是float64类型)。尽管如此,他的方法将你真正想要的内容分解开来,即将每个连续的数字(从右边开始)提升一个数量级,并将这些数字相加。因此,我能想到的最直接的方法是:

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的命名不太好,但你应该能理解这个思路。

这里是一个示例链接。

尽可能快地进行微小优化可能是一个选择,但如果它恰好在热路径上,这可能是值得的。

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
英文:

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

答案2

得分: 4

尝试这样做:

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

也许有更好的方法来实现这个功能,但这个示例是有效的。

英文:

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.

答案3

得分: 2

你可以使用循环遍历切片,并使用算术运算构建整数。

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

这段代码的功能是将切片 nums 中的数字按照从左到右的顺序构建成一个整数,并打印输出。

英文:

You can also iterate over the slice and build the int with arithmetic

package main

import (
	&quot;fmt&quot;
)

func Pow(a, b int) int {
	result := 1
	for i := 0; i &lt; 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)
}

答案4

得分: 0

遍历你的切片,并将每个项添加到缓冲区中:

var buf bytes.Buffer
nums := []int{1, 2, 3}
for i := range nums {
    buf.WriteString(fmt.Sprintf("%d", nums[i]))
}

然后,你可以使用strconv包将其转换为整数:

i, err := strconv.Atoi(buf.String())

在GoPlay中查看示例代码:
https://play.golang.org/p/8w-gc2S2xR

英文:

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(&quot;%d&quot;, 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

答案5

得分: 0

对我来说,最简单的方法是:

1)将int切片转换为string切片

2)连接字符串

3)将结果字符串转换为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))
}

结果:

123
1203

将int切片转换为字符串,然后连接起来的时间复杂度是O(N),而逐步构建最终字符串的时间复杂度是O(N * N)。

英文:

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, &quot;&quot;))
    
     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).

huangapple
  • 本文由 发表于 2017年6月24日 04:38:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/44729587.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定