0

I want to combine an integer array to a single integer value. So I have the following code that will combine the array to a single value.

int[] array = { 5, 6, 2, 4 };
int combine = 0;

for (int i = 0; i < array.Length; i++)
{
    combine += array[i] * Convert.ToInt32(Math.Pow(10, array.Length-i-1));
}

this yield combine = 5624. Which is correct.

My issue is my array is not in the form of 0-9. So my array could be {51,62,23,44}

int[] array = { 51, 62, 23, 44 };
int combine = 0;

for (int i = 0; i < array.Length; i++)
{
    combine += array[i] * Convert.ToInt32(Math.Pow(10, array.Length-i-1));
}

yielding combine as 574774, not 51622344. How would I correct this?

5
  • 6
    Convert each element to a string, concatenate the strings, and convert the result back to an Int32. Commented Jul 5, 2018 at 19:45
  • Why not convert them to strings and then concatenate? Commented Jul 5, 2018 at 19:45
  • Possible duplicate of C# List<string> to string with delimiter Commented Jul 5, 2018 at 19:50
  • @JayV: Not close enough. Commented Jul 5, 2018 at 19:51
  • thank you everyone. I have no idea why I didn't think of such a simple fix. Commented Jul 5, 2018 at 19:55

4 Answers 4

7

Do the following:

var number = int.Parse(string.Join("", array));

Explanation:

string.Join will take any enumeration of type T, call ToString() on each member and join them in a single string with the specified separator.

Once you have a string representing your number, you simply parse it to get the number itself.

Of course this is not safe and depending on your possible inputs, this could fail: {1, 4, -5, 4 }. Some error detection and int.TryParse is probably the best way to solve this, the example is simply to get the idea across.

Sign up to request clarification or add additional context in comments.

2 Comments

var number = int.Parse(string.Concat(array));
@Eser Yeah, I use Join quite a lot so I end up using it always. Concat is probably more correct, its a bad habit.
4

Why not convert them to strings and then concatenate?

using System;

public class Program
{
    public static void Main()
    {
        int[] intArray = { 5, 6, 2, 4 };
        var result = string.Concat(intArray);

        Console.WriteLine(result);

        try {
            int resultNumber = int.Parse(result);
        }
        catch(OverflowException) {
            // this can occur if you exceed the maximum value of an int
            long resultBigNumber = long.Parse(result);
        }
    }
}

2 Comments

Defining a result with a different type in a catch block is not the best idea.
@RobertHarvey - true but I am not sure how the end value is going to be used. If it is display only then the parsing is not needed at all and the whole try/catch can be ignored entirely. I guess there are still some question as to intent.
0

Try using a StringBuilder, like this:

using System;
using System.Text;
public class Program {
       public static void Main(string[] args) {
             StringBuilder sb = new StringBuilder();
             int[] array = new Int[] { 51, 62, 23, 44 };
             int combine = 0;
             foreach(int single in array) {
                    string oneNum = single.ToString();
                    sb.Append(oneNum);
             }
             string final = sb.ToString();
             combine = Convert.ToInt32(final);
       }
}

This will convert the numbers in the array into a string, which then gets converted into a number.

Comments

0

Linq and some simple math can help here (without strings or Math.Pow). I'm also going to seed it with numbers of widely varying magnitude (i.e., not all single digit numbers or all 2-digit numbers). First some preliminary code:

  private readonly int[] PowersOf10 = new [] {10, 100, 1000, 10000, 100000};
  private int DecimalShiftAccumulate(int numToShift, int numToAdd)
  {
      var nextPowerOf10 = PowersOf10.First(x => x > numToAdd);
      return (numToShift * nextPowerOf10) + numToAdd;
  }

You can include more numbers in the PowersOf10 array; I got tired of counting zeros.

Then declare your int array and calculate the result:

 var intArray = new[] { 1051, 7, 923, 44 };
 var arrayResult = intArray.Aggregate((a, b) => DecimalShiftAccumulate(a, b));

I get arrayesult = 1051792344 (i.e. (using & as concatenation) 1051 & 7 & 923 & 44)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.