简体   繁体   中英

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

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) ?

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

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.

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

Just did a benchmark on different methods and here is the results:

BenchmarkDotNet=v0.12.0, OS=Windows 10.0.19041
Intel Core i7-8705G CPU 3.10GHz (Kaby Lake G), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.1.301
  [Host]     : .NET Core 3.1.5 (CoreCLR 4.700.20.26901, CoreFX 4.700.20.27001), X64 RyuJIT
  DefaultJob : .NET Core 3.1.5 (CoreCLR 4.700.20.26901, CoreFX 4.700.20.27001), X64 RyuJIT


                         Method |      Mean |    Error |   StdDev |  Gen 0 | Gen 1 | Gen 2 | Allocated |
------------------------------- |----------:|---------:|---------:|-------:|------:|------:|----------:|
                          Stack |  89.06 ns | 2.130 ns | 6.179 ns | 0.0592 |     - |     - |     248 B |
                    SharedArray |  84.64 ns | 1.765 ns | 3.685 ns | 0.0153 |     - |     - |      64 B |
 PreallocateUsingNumberOfDigits |  39.15 ns | 0.861 ns | 2.499 ns | 0.0153 |     - |     - |      64 B |
                    IEnumerable | 246.53 ns | 4.926 ns | 9.372 ns | 0.0610 |     - |     - |     256 B |

In order mean speed:

PreallocateUsingNumberOfDigits

Mean: ~39.15ns Error: 0.861ns Alloc: 64 B

public static int[] GetDigits(int n)
{
    if (n == 0)
        return new[] {0};
    
    var x = Math.Abs(n);

    var numDigits = NumberOfDigits(x);

    var res = new int[numDigits];
    var count = 0;

    while (x > 0)
    {
        res[count++] = x % 10;
        
        x /= 10;
    }
    
    Array.Reverse(res);

    return res;
}

public static int NumberOfDigits(int n)
{
    if (n >= 0)
    {
        if (n < 10) return 1;
        if (n < 100) return 2;
        if (n < 1000) return 3;
        if (n < 10000) return 4;
        if (n < 100000) return 5;
        if (n < 1000000) return 6;
        if (n < 10000000) return 7;
        if (n < 100000000) return 8;
        if (n < 1000000000) return 9;
        return 10;
    }
    else
    {
        if (n > -10) return 2;
        if (n > -100) return 3;
        if (n > -1000) return 4;
        if (n > -10000) return 5;
        if (n > -100000) return 6;
        if (n > -1000000) return 7;
        if (n > -10000000) return 8;
        if (n > -100000000) return 9;
        if (n > -1000000000) return 10;
        return 11;
    }
}

SharedArray

Mean: ~84.64ns Error: 1.765ns Alloc: 64 B

public static int[] GetDigits_SharedPool(int n)
{
    if (n == 0)
        return new[] {0};
    
    var x = Math.Abs(n);
    
    var pool = ArrayPool<int>.Shared.Rent(11);
    var count = 0;

    while (x > 0)
    {
        pool[count++] = x % 10;
        
        x /= 10;
    }

    var res = new int[count];
    
    Array.Copy(pool, res, count);
    
    Array.Reverse(res);
    
    ArrayPool<int>.Shared.Return(pool);

    return res;
}

Stack

Mean: ~89.06ns Error: 2.130ns Alloc: 248 B

From: @Peter Lillevold answer

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

    return list.ToArray();
}

IEnumerable

Mean: ~246.53ns Error: 4.926ns Alloc: 256 B

From @Svish's Answer

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

Code

See here: michal-ciechan/GetDigitsBenchmark

简而言之:使用将数字除以 10 (%) 的循环来获取提醒(每个数字)并将其放入数组。

字符串并且可以很有趣(其他一些选项会更快......但这很容易)

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

.NET 4.7.1 or above:

IEnumerable<long> GetDigits(long value) =>
  value == 0 ? new long[0] : GetDigits(value / 10).Append(value % 10)

.NET 3.5 - 4.7:

IEnumerable<long> GetDigits(long value) =>
  value == 0 ? new long[0] : GetDigits(value / 10).Concat(new[] { value % 10 });

This converts the int value to string, then to an array of chars and finally to an int array.

var myInt = 31337;
var myIntArray = Array.ConvertAll(myInt.ToString().ToCharArray(), x => (int)Char.GetNumericValue(x));

I used .ToCharArray() because it should be faster than .ToArray() .

For the LINQ lovers as ONE LINER =>

var number = 8892366;
var splittedList = number.ToString().ToCharArray().Select(x => Int32.Parse(x.ToString())).ToList();

// Output : List<int> {8, 8, 9, 2, 3, 6, 6} 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM