1
$\begingroup$

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

  • 0
    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.2011-04-23
  • 0
    Out of curiosity: What is the motivation for this question?2011-04-23
  • 0
    @all: I edited the tags but wasn't sure which one to use in this case2011-04-23
  • 0
    @Leonardo Fontoura: Thank you @Theo Buehler: A part of a C++ program to building a wavefront planner for a course in robotics.2011-04-23
  • 0
    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.2011-04-23

1 Answers 1

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$.