Good way to "add" integers in C #?

I have two integers, for example. 15 and 6, and I want to get 156. What am I doing:

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

Best way to do this?

UPDATE: Thanks for all your good answers. I run a quick stopwatch test to find out what the performance implications are: This is the 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 is the time:

 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 good extension method for this solution.

+7
source share
5 answers

You can do it numerically. No string conversion required:

 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; 
+16
source

Here's the 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 use it:

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

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

0
source
 int i=15 int j=6 int result=i*10+6; 
-2
source

All Articles