Integer to Integer Array C#

前端 未结 14 1580
深忆病人
深忆病人 2020-12-08 04:42

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 :

publi         


        
14条回答
  •  无人及你
    2020-12-08 05:31

    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 result = new List();
        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.

提交回复
热议问题