Some Methods to Get the Number of Digits in An Integer, and Their Performance

16 Feb

Sometimes, we need to know the number of digits in an integer. There are many methods, which could do this work well. Here we list some of them, and compare their performance in different circumstances. Firstly, we post the source code of the testing program.

We tested the performance on Linux with Intel(R) Xeon(R) E5620 and 12G memory. The result is as following:


Total Running Time (for 0xFFFFFF Rounds), in seconds


The cost of log10 method is stable, no matter the number is big or small.
The sprintf method is always the slowest solution.
The division method is quick when the number is small.
The brute force method is ugly, but always efficient.
More discussion and an optimization solution for worst cases are in the next article here.

Leave a Reply

Your email address will not be published. Required fields are marked *

Please put your code into a <pre>YOUR CODE</pre> section. Thanks and Happy Coding!