Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert int array to int?

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.

like image 425
user1172635 Avatar asked Mar 05 '12 10:03

user1172635


People also ask

How do you turn an array into an int?

You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them.

Can we convert Integer array to Integer in Java?

Apache Commons Lang's ArrayUtils class provides toPrimitive() method that can convert an Integer array to primitive ints.


3 Answers

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));
}
like image 97
Dor Cohen Avatar answered Nov 19 '22 15:11

Dor Cohen


int output = array
    .Select((t, i) => t * Convert.ToInt32(Math.Pow(10, array.Length - i - 1)))
    .Sum();
like image 45
RichK Avatar answered Nov 19 '22 14:11

RichK


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.

like image 27
Shadow Wizard Hates Omicron Avatar answered Nov 19 '22 13:11

Shadow Wizard Hates Omicron