How to convert int array to int?

前端 未结 12 1937
小蘑菇
小蘑菇 2021-01-18 07:49

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:

相关标签:
12条回答
  • 2021-01-18 08:18

    In C# 3.0 and up:

    array.Select((t, i) => t * Convert.ToInt32(Math.Pow(10, array.Length - i - 1))).Sum();
    
    0 讨论(0)
  • 2021-01-18 08:20

    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.

    0 讨论(0)
  • 2021-01-18 08:24
    int output = array
        .Select((t, i) => t * Convert.ToInt32(Math.Pow(10, array.Length - i - 1)))
        .Sum();
    
    0 讨论(0)
  • 2021-01-18 08:27

    you can use string stream (include "sstream")

    using namespace std; int main(){

    int arr[3]={3,2,4};     //your array..
    
    stringstream ss;
    
    ss<<arr[0];   //this can be run as a loop
    ss<<arr[1];
    ss<<arr[2];
    
    
    int x;
    ss>>x;
    
    cout<<x;        //simply the int arr[3] will be converted to int x..
    
    0 讨论(0)
  • 2021-01-18 08:28

    This would be easy, if you have understood how the decimal system works.

    So let me explain that for you: A decimal digit contains single digits by base ten.

    This means you have to iterate through this array (backwards!) and multiply by 10^

    For an example 5624 means: (5*10^3) + (6*10^2) + (2*10^1) + (4*10^0)

    Please consider also: http://en.wikipedia.org/wiki/Horner_scheme

    0 讨论(0)
  • 2021-01-18 08:29

    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));
    }
    
    0 讨论(0)
提交回复
热议问题