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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
jas
  • 23
  • 1
  • 6

4 Answers4

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.

InBetween
  • 32,319
  • 3
  • 50
  • 90
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);
        }
    }
}
Igor
  • 60,821
  • 10
  • 100
  • 175
  • 1
    Defining a result with a different type in a `catch` block is not the best idea. – Robert Harvey Jul 05 '18 at 19:53
  • @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. – Igor Jul 05 '18 at 19:54
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)

Flydog57
  • 6,851
  • 2
  • 17
  • 18
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.