Is there an easy way to turn an int into an array of ints of each digit?

public Stack<int> NumbersIn(int value)
{
    if (value == 0) return new Stack<int>();

    var numbers = NumbersIn(value / 10);

    numbers.Push(value % 10);

    return numbers;
}

var numbers = NumbersIn(987654321).ToArray();

Alternative without recursion:

public int[] NumbersIn(int value)
{
    var numbers = new Stack<int>();

    for(; value > 0; value /= 10)
        numbers.Push(value % 10);

    return numbers.ToArray();
}

I know there are probably better answers than this, but here is another version:

You can use yield return to return the digits in ascending order (according to weight, or whatever it is called).

public static IEnumerable<int> Digits(this int number)
{
    do
    {
        yield return number % 10;
        number /= 10;
    } while (number > 0);
}

12345 => 5, 4, 3, 2, 1

Tags:

C#