18

I need to get count of a number like 12346 it must get the count of digits = 5

One way is that divide the number by 10 until remainder equals to zero.

Please tell me other approaches.

1 Answers1

24

The number of digits of a positive integer $n$ written in base $10$ is $\lfloor \log_{10} n\rfloor +1$. For example $\log_{10}12346 = 4.0915\dots$, so $$\lfloor\log_{10}n\rfloor + 1 = \lfloor 4.0915\dots \rfloor + 1 = 4 + 1 = 5.$$ To see why this works, note that if $n$ has $k$ digits, it satisfies $10^{k-1} \leq n < 10^k$. As the function $\log_{10}x$ is increasing, we have $k - 1 \leq \log_{10}n < k$ and hence $\lfloor\log_{10}n\rfloor = k - 1$. Adding $1$ to both sides gives the correct formula.

  • 2
    This fails for n = 0, a slight modification needs to be added to handle that case, if one assumes only positive $n$, a solution is max(n, 1) – Makogan Apr 08 '21 at 23:50