Is there an easy way to turn an int into an array

2019-01-02 21:56发布

问题:

Say I have

var i = 987654321;

Is there an easy way to get an array of the digits, the equivalent of

var is = new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 };

without .ToString()ing and iterating over the chars with int.Parse(x)?

回答1:

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();
}


回答2:

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



回答3:

Another alternative which don't uses recursion and uses a Stack that avoids reallocation on every insert (at least for the first 32 digits):

var list = new Stack<int>(32);
var remainder = 123456;
do
{
    list.Push(remainder % 10);
    remainder /= 10;
} while (remainder != 0);

return list.ToArray();

And yes, this method also works for 0 and negative numbers.

Interestingly, give this algorithm a negative number -123456 and you will get {-1, -2, -3, -4, -5, -6}

Update: switched from using List to Stack since this automatically gives the correct order.



回答4:

var x = new Stack<int>();
do
{
    x.Push(i % 10);
    i /= 10;
} while (i > 0);
return x.ToArray();


回答5:

In short: use loop which divide number modulo 10 (%) to get reminder (each digit) and put it into array.



回答6:

Strings and can fun (some of the other options would be faster... but this is pretty easy)

var @is = 987654321.ToString().Select(c => c - 48).ToArray();


回答7:

This does convert to string and iterate over the characters, but it does it sort of automatically and in a one-liner:

var i = 987654321;
var @is = i.ToString().Select(c => c - '0').ToArray();


标签: