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

后端 未结 11 806
天涯浪人
天涯浪人 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:42

    Millions of times isn't that much.

    // input: int num >= 0
    List digits = new List();
    while (num > 0)
    {
       byte digit = (byte) (num % 10);
       digits.Insert(0, digit);  // Insert to preserve order
       num = num / 10;
    }
    
    // if you really want it as an array
    byte[] bytedata = digits.ToArray();
    

    Note that this could be changed to cope with negative numbers if you change byte to sbyte and test for num != 0.

提交回复
热议问题