How to get digit count of an int?

I tried the following code but noticed that it is a bit slow. Any suggestions on how to improve it?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int count_digits(const int d)
{
       int place = 1; int mod = 10;
       if (d == 0)
              {
                     return 0;
              }
       else if (d > 0)
              for (int i = 0; i < d; ++i)
                     {
                            if ( (i % mod) == 9)
                                   {
                                          ++place;
                                          mod *= 10;
                                   }
                     }
       else
              for (int i = 0; i > d; --i)
                     {
                            if ( ( i % mod) == 9)
                                   {
                                          ++place;
                                          mod *=10;
                                   }
                     }
       return place;
}



Also there's a small bug in it somewhere.

It produces correct output from 0 through 99, and 110 through 999, and 1010 through 9999 etc. But input 100 through 109 and it will say it has 2 digits.
Last edited on
Scrap that and rethink.

Given any positive whole number, the number of digits are the number of times you can divide by ten before the number becomes zero.

1234 --> 123 --> 12 --> 1 --> 0
1 2 3 4

Given the number zero, the number of digits is one.

0

Given a negative integer, the number of digits is the number of digits when the number is negated.

-473 (negated) --> 473 --> 47 --> 4 --> 0
1 2 3

You don't need anything but pure integer division and a single loop, plus initial tests for zero and negative numbers.

Hope this helps.
Topic archived. No new replies allowed.