fastest way to find number of digits in number

133 Views Asked by At

What's the fastest way to determine the number of digits in a number?

Would it be like so:

const val = 10030504;
const numOfDigits = math.floor(math.divide(val, 10));

or perhaps faster to just convert to a string a get a length:

const s = String(val);
const numOfDigits = s.slice(0, s.indexOf('.')).length;

using string manipulations feels wrong.

1

There are 1 best solutions below

0
On BEST ANSWER

The comments discuss the (software) vulnerability to rounding errors of taking logarithms, base $10$.

Generally, programming languages such as Java, c, or Python, provide BigInteger facilities for just such a situation (i.e. when rounding errors must be avoided). Presumably, positive integers as large as $(10)^{(1000)}$ are routinely handled.

So, you can set the corresponding number to an object $A$ of the BigInteger class. Then, you can create a 2nd BigInteger object $B = 10.$

You can then determine exactly whether $B > A$. If not, multiply $B = B \times 10,$ and re-check whether $B > A$. Assuming that $A < (10)^{(1000)}$, your (very simple) program should routinely find the smallest value of $B$, using this algorithm, such that $B > A$.

Assuming that you maintain a counter $I1$, then if $(10)^{(I1)}$ is the smallest value of $B$ such that $B > A$, then $A$ has exactly $I1$ digits.