user194076
user194076

Reputation: 9027

Good way to "append" integers in C#?

I have two integers, ex. 15 and 6 and I want to get 156. What I do:

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

Any better way of doing this?

UPDATE: Thanks for all of your nice answers. I run a quick Stopwatch test to see what are the performance implications: This is a code tested on my machine:

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

And here's the timing:

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 provided a very nice and smart solution and Chris Gessler provided a very nice extension method for that solution.

Upvotes: 7

Views: 2842

Answers (5)

Chris Gessler
Chris Gessler

Reputation: 23123

Here's an Extension method:

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

And to use it:

    int x = 123;
    int y = x.Append(4).Append(5).Append(6).Append(789);
    Console.WriteLine(y);

Upvotes: 3

shenhengbin
shenhengbin

Reputation: 4294

I would like to use string.Concat(i,j)

Upvotes: 0

yapingchen
yapingchen

Reputation: 866

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

Upvotes: -2

Pent Ploompuu
Pent Ploompuu

Reputation: 5414

int res = j == 0 ? i : i * (int)Math.Pow(10, (int)Math.Log10(j) + 1) + j;

Upvotes: 2

Guffa
Guffa

Reputation: 700592

You can do it numerically. No string conversion needed:

int i=15;
int j=6;

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

or:

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

Upvotes: 16

Related Questions