int count_digits(constint d)
{
int place = 1; int mod = 10;
if (d == 0)
{
return 0;
}
elseif (d > 0)
for (int i = 0; i < d; ++i)
{
if ( (i % mod) == 9)
{
++place;
mod *= 10;
}
}
elsefor (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.
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.