Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good way to "append" integers in C#?

Tags:

c#

integer

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.

like image 676
user194076 Avatar asked Jul 04 '12 00:07

user194076


3 Answers

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;
like image 135
Guffa Avatar answered Nov 12 '22 13:11

Guffa


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);
like image 28
Chris Gessler Avatar answered Nov 12 '22 12:11

Chris Gessler


int res = j == 0 ? i : i * (int)Math.Pow(10, (int)Math.Log10(j) + 1) + j;
like image 38
Pent Ploompuu Avatar answered Nov 12 '22 12:11

Pent Ploompuu