D
David Resnick
Jordan said:Richard said:Ohh my.... didn't think it would be a two liner.......thank you
#include<math.h>
int numdigits(int n)
return log10(n) + 1;
I don't think a floating-point solution is best here. A loop using
integer arithmetic is likely to be faster and more accurate. For that
matter, a binary search on a lookup table holding powers of 10 is
likely to be even quicker.
*g* Never knock the simple solution. You're quite right, of course
How about:
int length;
char digits[100]; /* should be big enough even for 128 bit longs */
sprintf(digits, "%d", n);
length = strlen(digits) - (n<0 ? 1 : 0);
For c99:
length = snprintf(0,0,"%d",n)-1;
Why the -1?
[#3] The snprintf function returns the number of characters
that would have been written had n been sufficiently large,
not counting the terminating null character, or a negative
value if an encoding error occurred. Thus, the null-
terminated output has been completely written if and only if
the returned value is nonnegative and less than n.
Return count doesn't include the terminating null. Sanity check on
this
with gcc:
temp(1186)$ cat foo.c
#include <stdio.h>
int main(void)
{
int foo = 10;
size_t len = snprintf(NULL, 0, "%d", foo);
printf("%d has len %lu\n", foo, (unsigned long) len);
return 0;
}
temp(1187)$ gcc -Wall -pedantic foo.c -o foo
temp(1188)$ foo
10 has len 2
-David