Fastest way to separate the digits of an int into an array in .NET?

后端 未结 11 976
天涯浪人
天涯浪人 2021-01-31 20:07

I want to separate the digits of an integer, say 12345, into an array of bytes {1,2,3,4,5}, but I want the most performance effective way to do that, because my program does tha

11条回答
  •  没有蜡笔的小新
    2021-01-31 20:44

    1 + Math.Log10(num) will give the number of digits without any searching/looping:

    public static byte[] Digits(int num)
    {
        int nDigits = 1 + Convert.ToInt32(Math.Floor(Math.Log10(num)));
        byte[] digits = new byte[nDigits];
        int index = nDigits - 1;
        while (num > 0) {
            byte digit = (byte) (num % 10);
            digits[index] = digit;
            num = num / 10;
            index = index - 1;
        }
        return digits;
    }
    

    Edit: Possibly prettier:

    public static byte[] Digits(int num)
    {
        int nDigits = 1 + Convert.ToInt32(Math.Floor(Math.Log10(num)));
        byte[] digits = new byte[nDigits];
    
        for(int i = nDigits - 1; i != 0; i--)
        {
            digits[i] = (byte)(num % 10);
            num = num / 10;
        }
        return digits;
    } 
    

提交回复
热议问题