Search code examples
c#arraysint

Integer to Integer Array C#


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;
}

Solution

  • 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;
    }