Concatenate ints inside array golang – GoLang

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

Concatenate ints inside array golang - GoLang

问题

我有一个包含3个位置的数组,假设它们都是数字5。

[5 5 5]

我该如何将它传递给一个变量,使得它保持为555?就像这样。

n := 555
英文:

I have an array with 3 positions, imagine it has the number 5 in all of them.

[5 5 5]

how can I pass it to a var in a way that it stays 555? just like this.

n:= 555 

答案1

得分: 6

你可以像在其他语言中一样进行操作:

s := []int{1, 2, 3}
n := 0
for _, sn := range s {
    n *= 10
    n += sn
}

Playground: http://play.golang.org/p/SSemwbJuTz.

编辑: 如果你计划处理的数字不仅限于个位数,那么循环会有些复杂:

for _, sn := range s {
    shift := 10
    for shift < sn {
        shift *= 10
    }
    n *= shift
    n += sn
}

这个方法适用于像[]int{1, 23, 456}这样的输入:http://play.golang.org/p/h1xsu9vtmP.

但要注意整数溢出的问题。

英文:

The same way you would in any other language:

s := []int{1, 2, 3}
n := 0
for _, sn := range s {
	n *= 10
	n += sn
}

Playground: http://play.golang.org/p/SSemwbJuTz.

Edit: if you're planning to work with more that just single-digit numbers, the loop is a bit trickier:

for _, sn := range s {
	shift := 10
	for shift &lt; sn {
		shift *= 10
	}
	n *= shift
	n += sn
}

This works with inputs like []int{1, 23, 456}: http://play.golang.org/p/h1xsu9vtmP.

Look out for the integer overflow though.

答案2

得分: 1

如果你想要将结果作为字符串输出:

package main

import "fmt"
import "strconv"

func main() {
    fmt.Println("Hello, playground")
    a := []int{1, 2, 3, 4}
    s := ""
    for _, c := range a {
        s += strconv.Itoa(c)
    }
    fmt.Println(s)
}

如果你想要将结果作为字符串输出。

英文:

If you want to have result as string

package main

import &quot;fmt&quot;
import &quot;strconv&quot;

func main() {
	fmt.Println(&quot;Hello, playground&quot;)
	a := []int{1, 2, 3,4}
	s := &quot;&quot;
	for _, c := range a {
   		s += strconv.Itoa(c)
	}
	fmt.Println(s)
}

huangapple
  • 本文由 发表于 2015年8月17日 21:26:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/32051653.html
匿名

发表评论

匿名网友

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

确定