Richard Bos schrieb:
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);
Boxing this code in a function and/or handling special cases (has 0 1
digit or none?) is left as exercise for the OP.