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.
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;
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);
int res = j == 0 ? i : i * (int)Math.Pow(10, (int)Math.Log10(j) + 1) + j;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With