繁体   English   中英

在C#中“追加”整数的好方法?

[英]Good way to “append” integers in C#?

我有两个整数,例如。 15和6,我想得到156.我做了什么:

int i = 15;
int j = 6;
Convert.ToInt32(i.ToString() + j.ToString());

有没有更好的方法呢?

更新:谢谢你所有的好答案。 我运行快速秒表测试以查看性能影响:这是在我的机器上测试的代码:

static void Main()
    {
        const int LOOP = 10000000;
        int a = 16;
        int b = 5;
        int result = 0;
        Stopwatch sw = Stopwatch.StartNew();
        for (int i = 0; i < LOOP; i++)
        {
            result = AppendIntegers3(a, b);
        }
        sw.Stop();
        Console.WriteLine("{0}ms, LastResult({1})", sw.ElapsedMilliseconds,result);
    }

这是时间:

My original attempt: ~3700ms 
Guffa 1st answer: ~105ms 
Guffa 2nd answer: ~110ms 
Pent Ploompuu answer: ~990ms 
shenhengbin answer: ~3830ms 
dasblinkenlight answer: ~3800ms
Chris Gessler answer: ~105ms

Guffa提供了一个非常好的智能解决方案,Chris Gessler为该解决方案提供了一个非常好的扩展方法。

你可以用数字来做。 无需字符串转换:

int i=15;
int j=6;

int c = 1;
while (c <= j) {
  i *= 10;
  c *= 10;
}
int result = i + j;

要么:

int c = 1;
while (c <= j) c *= 10;
int result = i * c + j;

这是一个扩展方法:

public static class Extensions
{
    public static int Append(this int n, int i)
    {
        int c = 1;
        while (c <= i) c *= 10;
        return n * c + i; 
    }
}

并使用它:

    int x = 123;
    int y = x.Append(4).Append(5).Append(6).Append(789);
    Console.WriteLine(y);
int res = j == 0 ? i : i * (int)Math.Pow(10, (int)Math.Log10(j) + 1) + j;

我想用string.Concat(i,j)

int i=15
int j=6
int result=i*10+6;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM