Golang:合并两个数字

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

Golang: Combine two numbers

问题

你好!以下是你要翻译的内容:

我感觉很愚蠢问这个问题,但是我该如何在GO中实现以下操作?

假设我有两个int32变量,它们的值都是33。
我该如何将它们合并成一个值为3333的int32,而不是66?

英文:

I feel quite stupid asking this but how can I archive the following in GO?

Let's say I have two int32 which both have the value 33.
How can I combine them into one int32 with the value 3333 instead of 66?

答案1

得分: 9

  1. var a, b int32 = 33, 33
  2. a = a*100 + b
  3. fmt.Println(a)

Playground.

编辑: 这是一个根据数字计算填充的版本:

  1. func main() {
  2. var a, b int32 = 1234, 456
  3. a = a*padding(b) + b
  4. fmt.Println(a)
  5. }
  6. func padding(n int32) int32 {
  7. var p int32 = 1
  8. for p < n {
  9. p *= 10
  10. }
  11. return p
  12. }

Playground.

请注意,您还应该检查 int32 是否会溢出。如果您不想担心溢出,可以使用 big.Int

英文:
  1. var a, b int32 = 33, 33
  2. a = a*100 + b
  3. fmt.Println(a)

Playground.

Edit: Here is a version which computes the padding depending on the number:

  1. func main() {
  2. var a, b int32 = 1234, 456
  3. a = a*padding(b) + b
  4. fmt.Println(a)
  5. }
  6. func padding(n int32) int32 {
  7. var p int32 = 1
  8. for p &lt; n {
  9. p *= 10
  10. }
  11. return p
  12. }

Playground.

Note that you should also check that int32 won't overflow. If you don't want to worry about overflows, you can use a big.Int instead.

答案2

得分: 4

我对性能与Ainar-G的解决方案相比没有什么概念,但是对于这个代码片段,你可以尝试以下方式:

  1. var a, b int32 = 33, 33
  2. result, err := strconv.Atoi(fmt.Sprintf("%d%d", a, b))
  3. if err != nil {
  4. panic(err)
  5. }
  6. fmt.Println(int32(result))

这段代码的作用是将两个整数 ab 拼接成一个字符串,然后使用 strconv.Atoi 函数将该字符串转换为整数,并将结果打印出来。如果转换过程中出现错误,会触发一个 panic。

英文:

I have no idea about the performance, compared to Ainar-G's solution, but what about this:

  1. var a, b int32 = 33, 33
  2. result, err := strconv.Atoi(fmt.Sprintf(&quot;%d%d&quot;, a, b))
  3. if err != nil {
  4. panic(err)
  5. }
  6. fmt.Println(int32(result))

huangapple
  • 本文由 发表于 2015年1月20日 00:41:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/28029518.html
匿名

发表评论

匿名网友

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

确定