1

This question is a bit basic, but how do I check the number of digits in an integer?

I need to check if an integer P is between 100 and 0 without doing an if condition simliar to (P>9)&&(P<100)?

Something like P%100==0? (where % is mod)

Thanks

t.b.
  • 78,116
R.J.
  • 183
  • I think one of the most straightforward ways would be to check the rest of the division first by 10, then by 100, etc, until you get rest == 0. Then you count how many times you got a rest that was not 0, and that is your number of digits. There might be a smtarter way of checking it thought. – Leonardo Fontoura Apr 23 '11 at 05:34
  • Out of curiosity: What is the motivation for this question? – t.b. Apr 23 '11 at 05:35
  • @all: I edited the tags but wasn't sure which one to use in this case – t.b. Apr 23 '11 at 05:41
  • @Leonardo Fontoura: Thank you

    @Theo Buehler: A part of a C++ program to building a wavefront planner for a course in robotics.

    – R.J. Apr 23 '11 at 06:52
  • You can check if P%100 == P; that will be "yes" for $0\leq P\leq 99$, but no for $P\lt 0$ and $p\geq 100$. If you want to include $100$, then do P%101==P. – Arturo Magidin Apr 23 '11 at 07:13

1 Answers1

4

If you know you have a positive integer $n$, $\lfloor\log_{10}n\rfloor+1$ (that is, floor(log10(n))+1) will give the number of digits in $n$.

Isaac
  • 36,557