Integer to Integer Array C#

此生再无相见时 提交于 2019-12-28 11:46:12

问题


I had to split an int "123456" each value of it to an Int[] and i have already a Solution but i dont know is there any better way : My solution was :

public static int[] intToArray(int num){
    String holder = num.ToString();
    int[] numbers = new int[Holder.ToString().Length]; 
    for(int i=0;i<numbers.length;i++){
        numbers[i] = Convert.toInt32(holder.CharAt(i));
    }
    return numbers;
}

回答1:


I believe this will be better than converting back and forth. As opposed to JBSnorro´s answer I reverse after converting to an array and therefore avoid IEnumerable´s which I think will contribute to a little bit faster code. This method work for non negative numbers, so 0 will return new int[1] { 0 }.

If it should work for negative numbers, you could do a n = Math.Abs(n) but I don't think that makes sense.

Furthermore, if it should be more performant, I could create the final array to begin with by making a binary-search like combination of if-statements to determine the number of digits.

public static int[] digitArr(int n)
{
    if (n == 0) return new int[1] { 0 };

    var digits = new List<int>();

    for (; n != 0; n /= 10)
        digits.Add(n % 10);

    var arr = digits.ToArray();
    Array.Reverse(arr);
    return arr;
}

Update 2018:

public static int numDigits(int n) {
    if (n < 0) {
        n = (n == Int32.MinValue) ? Int32.MaxValue : -n;
    }
    if (n < 10) return 1;
    if (n < 100) return 2;
    if (n < 1000) return 3;
    if (n < 10000) return 4;
    if (n < 100000) return 5;
    if (n < 1000000) return 6;
    if (n < 10000000) return 7;
    if (n < 100000000) return 8;
    if (n < 1000000000) return 9;
    return 10;
}

public static int[] digitArr2(int n)
{
    var result = new int[numDigits(n)];
    for (int i = result.Length - 1; i >= 0; i--) {
        result[i] = n % 10;
        n /= 10;
    }
    return result;
}



回答2:


A simple solution using LINQ

 int[] result = yourInt.ToString().Select(o=> Convert.ToInt32(o)).ToArray()



回答3:


int[] outarry = Array.ConvertAll(num.ToString().ToArray(), x=>(int)x);

but if you want to convert it to 1,2,3,4,5:

int[] outarry = Array.ConvertAll(num.ToString().ToArray(), x=>(int)x - 48);



回答4:


Using conversion from int to string and back probably isn't that fast. I would use the following

public static int[] ToDigitArray(int i)
{
    List<int> result = new List<int>();
    while (i != 0)
    {
        result.Add(i % 10);
        i /= 10;
    }
    return result.Reverse().ToArray();
}

I do have to note that this only works for strictly positive integers.

EDIT:

I came up with an alternative. If performance really is an issue, this will probably be faster, although you can only be sure by checking it yourself for your specific usage and application.

public static int[] ToDigitArray(int n)
{
    int[] result = new int[GetDigitArrayLength(n)];
    for (int i = 0; i < result.Length; i++)
    {
        result[result.Length - i - 1] = n % 10;
        n /= 10;
    }
    return result;
}
private static int GetDigitArrayLength(int n)
{
    if (n == 0)
        return 1;
    return 1 + (int)Math.Log10(n);
}

This works when n is nonnegative.




回答5:


I'd do it like this:

var result = new List<int>();
while (num != 0) {
    result.Insert(0, num % 10);
    num = num / 10;
}
return result.ToArray();

Slightly less performant but possibly more elegant is:

return num.ToString().Select(c => Convert.ToInt32(c.ToString())).ToArray();

Note that these both return 1,2,3,4,5,6 rather than 49,50,51,52,53,54 (i.e. the byte codes for the characters '1','2','3','4','5','6') as your code does. I assume this is the actual intent?




回答6:


You can do that without converting it to a string and back:

public static int[] intToArray(int num) {
  List<int> numbers = new List<int>();
  do {
    numbers.Insert(0, num % 10);
    num /= 10;
  } while (num > 0);
  return numbers.ToArray();
}

It only works for positive values, of course, but your original code also have that limitation.




回答7:


string DecimalToBase(int iDec, int numbase)
        {
            string strBin = "";
            int[] result = new int[32];
            int MaxBit = 32;
            for(; iDec > 0; iDec/=numbase)
            {
                int rem = iDec % numbase;
                    result[--MaxBit] = rem;
            } 
            for (int i=0;i<result.Length;i++)
                if ((int)result.GetValue(i) >= base10)
                    strBin += cHexa[(int)result.GetValue(i)%base10];
                else
                    strBin += result.GetValue(i);
            strBin = strBin.TrimStart(new char[] {'0'});
            return strBin;
        }
        int BaseToDecimal(string sBase, int numbase)
        {
            int dec = 0;
            int b;
            int iProduct=1;
            string sHexa = "";
            if (numbase > base10)
                for (int i=0;i<cHexa.Length;i++)
                    sHexa += cHexa.GetValue(i).ToString();
            for(int i=sBase.Length-1; i>=0; i--,iProduct *= numbase)
            {
                string sValue = sBase[i].ToString();
                if (sValue.IndexOfAny(cHexa) >=0)
                    b=iHexaNumeric[sHexa.IndexOf(sBase[i])];
                else 
                    b= (int) sBase[i] - asciiDiff;
                dec += (b * iProduct);
            } 
            return dec; 
        }



回答8:


i had similar requirement .. i took from many good ideas, and added a couple missing pieces .. where many folks weren’t handling zero or negative values. this is what i came up with:

    public static int[] DigitsFromInteger(int n)
    {
        int _n = Math.Abs(n);
        int length = ((int)Math.Log10(_n > 0 ? _n : 1)) + 1;
        int[] digits = new int[length];
        for (int i = 0; i < length; i++)
        {
            digits[(length - i) - 1] = _n % 10 * ((i == (length - 1) && n < 0) ? -1 : 1);
            _n /= 10;
        }
        return digits;
    }

i think this is pretty clean .. although, it is true we're doing a conditional check and several extraneous calculations with each iteration .. while i think they’re nominal in this case, you could optimize a step further this way:

    public static int[] DigitsFromInteger(int n)
    {
        int _n = Math.Abs(n);
        int length = ((int)Math.Log10(_n > 0 ? _n : 1)) + 1;
        int[] digits = new int[length];
        for (int i = 0; i < length; i++)
        {
            //digits[(length - i) - 1] = _n % 10 * ((i == (length - 1) && n < 0) ? -1 : 1);
            digits[(length - i) - 1] = _n % 10;
            _n /= 10;
        }
        if (n < 0)
            digits[0] *= -1;
        return digits;
    }



回答9:


Thanks to ASCII character table. The simple answer using LINQ above yields answer + 48.

Either

int[] result = youtInt.ToString().Select(o => Convert.ToInt32(o) - 48).ToArray();

or

int[] result = youtInt.ToString().Select(o => int.Parse(o.ToString())).ToArray();

can be used




回答10:


Here is a Good Solution for Convert Your Integer into Array i.e: int a= 5478 into int[] There is no issue if You Have a String and You want to convert a String into integer Array for example string str=4561; //Convert into
array[0]=4;
array[1]=5;
array[2]=6;
array[3]=7;

Note: The Number of zero (0) in devider are Equal to the Length of input and Set Your Array Length According to Your input length
Now Check the Coding:

         string str=4587;
            int value = Convert.ToInt32(str);
            int[] arr = new int[4];
            int devider = 10000;
            for (int i = 0; i < str.Length; i++)
            {
                int m = 0;
                devider /= 10;
                arr[i] = value / devider;
                m = value / devider;
                value -= (m * devider);
            }



回答11:


 private static int[] ConvertIntToArray(int variable)
        {
            string converter = "" + variable;
            int[] convertedArray = new int[converter.Length];
            for (int i=0; i < convertedArray.Length;i++) //it can be also converter.Length
            {
                convertedArray[i] = int.Parse(converter.Substring(i, 1));
            }
            return convertedArray;
        }

We get int via using method. Then, convert it to string immediately (123456->"123456"). We have a string called converter and carry to int value. Our string have a string.Length, especially same length of int so, we create an array called convertedArray that we have the length, that is converter(string) length. Then, we get in the loop where we are convert the string to int one by one via using string.Substring(i,1), and assign the value convertedArray[i]. Then, return the convertedArray.At the main or any method you can easily call the method.




回答12:


public static int[] intToArray(int num)
{
    num = Math.Abs(num);
    int length = num.ToString().Length;
    int[] arr = new int[length];
    do
    {
        arr[--length] = num % 10;
        num /= 10;
    } while (num != 0);

    return arr;
}

Dividing by system base (decimal in this case) removes the right most digit, and we get that digit by remainder operator. We keep repeating until we end up with a zero. Each time a digit is removed it will be stored in an array starting from the end of the array and backward to avoid the need of revering the array at the end. The Math.Abs() function is to handle the negative input, also the array is instantiated with the same size as input length.



来源:https://stackoverflow.com/questions/4580261/integer-to-integer-array-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!