从C#中获取单独的数字

EhM*_*365 4 .net c# int

当我需要从数字本身的各个数字计算一个支票号码/数字时,我偶然发现了这个挑战.

例如,我有数字(Int32)423594340,我想要一个整数集合4,2,3,5,9,4,3,0.

我认为最好不要因为性能而将给定int转换为a String. 但你怎么做呢?

EhM*_*365 7

我提出了个人困惑的解决方案.

#1:自己创建的解决方案

public static IEnumerable<int> GetDigits(int source)
{
    int individualFactor = 0;
    int tennerFactor = Convert.ToInt32(Math.Pow(10, source.ToString().Length));
    do
    {
        source -= tennerFactor * individualFactor;
        tennerFactor /= 10;
        individualFactor = source / tennerFactor;

        yield return individualFactor;
    } while (tennerFactor > 1);
}
Run Code Online (Sandbox Code Playgroud)

#2:与Linq的.Reverse()模数

之后我在Internet上探索了其他解决方案,我从Java 人员那里得到了一个:如何获取一个int数字的单独数字?

缺点是集合中的整数顺序是相反的.这是微软的Linq.

如何调用方法.Reverse().

...
GetDigits2(input).Reverse()
...
Run Code Online (Sandbox Code Playgroud)

而实际的方法.

public static IEnumerable<int> GetDigits2(int source)
{
    while (source > 0)
    {
        var digit = source % 10;
        source /= 10;
        yield return digit;
    }
}
Run Code Online (Sandbox Code Playgroud)

#3:使用Stack的LIFO模数

当我不想考虑.Revers()在方法(GetDigits2(int source))之后调用时,我还能做什么?所以我在方法中使用变量,对变量调用.Reverse()并返回其结果.

或者完全不同的东西:我记得LIFO逻辑.在.NET中,您可以使用Stack类.

public static IEnumerable<int> GetDigits3(int source)
{
    Stack<int> digits = new Stack<int>();
    while (source > 0)
    {
        var digit = source % 10;
        source /= 10;
        digits.Push(digit);
    }

    return digits;
}
Run Code Online (Sandbox Code Playgroud)

测试

我测试了每种方法1000万次,并测量了测试开始和结束之间的滴答数.

#1:拥有创建的方法

1'549'084 ticks
Run Code Online (Sandbox Code Playgroud)

#2:与Linq的.Reverse()模数

2'252'875 ticks
Run Code Online (Sandbox Code Playgroud)

#3:使用Stack的LIFO模数

23'626'839 ticks
Run Code Online (Sandbox Code Playgroud)

TL;博士

这是小提琴:从int获取数字

  • @MightyBadaboom [完全没问题](https://stackoverflow.com/help/self-answer) (5认同)