Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get separate digits from int in C# [duplicate]

Tags:

c#

.net

int

I stumbled across this challenge when I needed to calculate a check number/digit from the individual digits of the number itself.

E.g. I have the number (Int32) 423594340 and I want a collection of integers like 4,2,3,5,9,4,3,0.

I think it is better to not convert the given int into a String because of performance. But how do you do that instead?

like image 399
bvwidt Avatar asked Aug 04 '17 13:08

bvwidt


1 Answers

I came up with an individual puzzled out solution.

#1: Own created solution

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

#2: Modulo with Linq's .Reverse()

After that I explored the Internet for other solutions and I came across one from the Java folks: How to get the separate digits of an int number?

The downside is that the order of integers in the collection is reversed. Here comes Microsoft's Linq.

How to call the method with .Reverse().

...
GetDigits2(input).Reverse()
...

And the actual method.

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

#3: Modulo with Stack's LIFO

What else could I do when I do not want to think about calling .Revers() after the method (GetDigits2(int source))? So I use a variable inside the method, call .Reverse() on the variable and return its result instead.

Or something totally different: I remember the LIFO logic. In .NET you use the Stack class for that.

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

Testing

I tested each method 10 million times and measured the number of tickes between start and end of the test.

#1: Own Created method

1'549'084 ticks

#2: Modulo with Linq's .Reverse()

2'252'875 ticks

#3: Modulo with Stack's LIFO

23'626'839 ticks

tl;dr

Here comes the fiddle: Get Digits from int

like image 139
bvwidt Avatar answered Nov 13 '22 11:11

bvwidt