【问题标题】:How to add a number on the end of another number如何在另一个数字的末尾添加一个数字
【发布时间】:2016-06-19 18:25:39
【问题描述】:

我想将一个号码加入另一个号码而不是添加它。

示例:我希望它而不是 1 + 1 生成 2,而是生成 11

我想我唯一能做的就是+ 1,但这只是让它变成2,我希望它变成11。

【问题讨论】:

  • 你到底在问什么?

标签: c# .net


【解决方案1】:

如果我明白你的要求,你想要这个:

1 + 1 = 11

而不是:

1 + 1 = 2

为此,只需将数字转换为字符串并将它们连接起来。然后您可以将结果转换回数字。

string result = 1.ToString() + 1.ToString(); // or, "1" + "1"
result == "11";
int numberResult = Convert.ToInt32(result);

【讨论】:

    【解决方案2】:

    您可以通过使用指数和对数来避免字符串实例化和转换:

    public static int Concat(int x, int y)
    {
        return x * (int)Math.Pow(10, Math.Floor(Math.Log(y, 10)) + 1) + y;
    }
    

    这是通过将 x 乘以 10 的幂来实现的,该幂的零与 y 的数字一样多,然后只需将 y 相加即可。数学上:x × 10⌊log10y⌋ + 1 + y

    这将导致两个数字的十进制表示似乎已连接在一起。 例如:

    Concat(1, 1)      :  1 *     10 +     1
    Concat(3, 54)     :  3 *    100 +    54
    Concat(28, 999)   : 28 *   1000 +   999
    Concat(76, 84215) : 76 * 100000 + 84215
    

    如果您知道您的数字通常很小,您可以编写热路径以避免计算量大的 PowLog 操作:

    public static int Concat(int x, int y)
    {
        if (y < 10)     return x * 10 + y;
        if (y < 100)    return x * 100 + y;
        if (y < 1000)   return x * 1000 + y;
        if (y < 10000)  return x * 10000 + y;
    
        return x * (int)Math.Pow(10, Math.Floor(Math.Log(y, 10)) + 1) + y;
    }
    

    【讨论】:

      【解决方案3】:

      如果您需要在代码中多次添加它,最好创建这样的函数:

      public static int JoinNumber(int x, int y)
      {
          int z = 0;
          string temp = Convert.ToString(x) + Convert.ToString(y);
          z = Convert.ToInt32(temp);
          return z;
      }
      

      public static int JoinNumber(int x, int y)
      {
          return Convert.ToInt32(Convert.ToString(x) + Convert.ToString(y));
      }
      

      您需要根据您的要求为 long 和其他类型创建重载。

      【讨论】:

        【解决方案4】:

        你想要的只是:

        string result = String.Concat(1, 1);
        

        真的,仅此而已。

        如果您想返回一个整数值,原因不明:

        int result = Int32.Parse(String.Concat(1, 1));
        

        小心溢出。

        【讨论】:

          猜你喜欢
          • 2021-02-14
          • 1970-01-01
          • 1970-01-01
          • 2016-01-03
          • 2010-10-10
          • 2014-02-23
          • 1970-01-01
          • 1970-01-01
          • 2013-01-15
          相关资源
          最近更新 更多