How to convert int array to int?

49,754

Solution 1

simply multiply each number with 10^ his place in the array.

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

Solution 2

int output = array
    .Select((t, i) => t * Convert.ToInt32(Math.Pow(10, array.Length - i - 1)))
    .Sum();

Solution 3

Another simple way:

int[] array =  {5, 6, 2, 4};
int num;
if (Int32.TryParse(string.Join("", array), out num))
{
    //success - handle the number
}
else
{
    //failed - too many digits in the array
}

Trick here is making the array a string of digits then parsing it as integer.

Solution 4

Use this code you just want to concatenate you int array so use the following code

String a;
int output;
int[] array = {5, 6, 2, 4};
foreach(int test in array)
{
a+=test.toString();
}
output=int.parse(a);
//where output gives you desire out put

This is not an exact code.

Solution 5

int result = 0;
int[] arr = { 1, 2, 3, 4};
int multipicator = 1;
for (int i = arr.Length - 1; i >= 0; i--)
{
   result += arr[i] * multipicator;
   multipicator *= 10;
}
Share:
49,754
user1172635
Author by

user1172635

Updated on June 01, 2021

Comments

  • user1172635
    user1172635 almost 3 years

    What I would like to learn how to do is to convert an int array to an int in C#.

    However I want to append the int with the values from the array.

    Example:

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

    Would be converted into an int that equals 5624.

    Thanks for any help in advance.