Split number into groups of 3 digits

c#, parsing

Solution

Without converting to string:

int[] splitNumber(int value)
{ 
    Stack<int> q = new Stack<int>();
    do 
    {
        q.Push(value%1000);
        value /= 1000;
    } while (value>0);
    return q.ToArray();
}

This is simple integer arithmetic; first take the modulo to get the right-most decimals, then divide to throw away the decimals you already added. I used the Stack to avoid reversing a list.

Edit: Using log to get the length was suggested in the comments. It could make for slightly shorter code, but in my opinion it is not better code, because the intent is less clear when reading it. Also, it might be less performant due to the extra Math function calls. Anyways; here it is:

int[] splitNumber(int value)
{
    int length = (int) (1 + Math.Log(value, 1000));
    var result = from n in Enumerable.Range(1,length)
                 select ((int)(value / Math.Pow(1000,length-n))) % 1000;
    return result.ToArray();           
}

Problem

I want to make a method that takes a variable of type `int` or `long` and returns an array of `int`s or `long`s, with each array item being a group of 3 digits. For example: ``` int[] i = splitNumber(100000); // Outputs { 100, 000 } int[] j = splitNumber(12345); // Outputs { 12, 345 } int[] k = splitNumber(12345678); // Outputs { 12, 345, 678 } // Et cetera ``` I know how to get the last n digits of a number using the modulo operator, but I have no idea how to get the first n digits, which is the only way to make this method that I can think of. Help please!

Original source