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.

  • 3
    $\begingroup$ Taking the integer part of $\log_{10}$ and adding $1$ suit you? $\endgroup$ – Macavity Aug 17 '13 at 9:02

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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.