Parsing a number into digits

featured
March 11, 2017
💫 Originally posted here. Broken? Let me know ~

Featured Image – “Miss South Carolina Powerset Parse” by official_powerset, used under BY SA / Dropped Quality to 80% from original

I’ve run into situations where I had to parse a number into digits.

An easy way to do this is to convert a number into a string and returns a character array, and then convert each character into a number

When dealing with large sets of long numbers, it simply is not optimal.

There is a simple way to convert a number into digits, which requires a simple math.

Given an integer  “val =213”, one might consider converting it to a string, breaking it to a character array and convert each character into an integer (it’s so simple in LINQ, it’s just tempting to implement it this way).

The cost of type conversion from an integer to a string, to an array, and then back to integer is too high.

Now let’s take a look at another way using a simple math.

Given an integer 213, if you

  1. divide it by 1 and mod 10, you get 3
  2. divide it by 10 and mod 10, you get 1
  3. divide it by 100 and mod 10, you get 2

If you look at the returned result, it’s each digit returned in reverse order. There is a useful data structure, for holding data in reverse order, Stack.

An algorithm is fairly simple.

While the given number is greater than 0, divide it by 10^digit, put the digit into a stack, and lastly return the stack as a list.

During each iteration, “number” is divided by 10 so it is equivalent to dividing by 10^digit.

I did a simple benchmarking (contrived but works for a simple demo) and the one requiring a type conversion to a string ran about 2x as long.

Result:

The source code is available on GitHub.

Conclusion

By using simple math, you can extract digits from a number.

It requires no type conversion thus saving run time.