int digits( int n ){ int i=0; if (n<0) n= -n; while (n) { n/=10; i++; } return i;}
No biggy of course, everyone should be able to do this. So, now lets see some impressive methods.
int digits( int n ){ int i=0; if (n<0) n= -n; while (n) { n/=10; i++; } return i;}
Quote:Original post by Inmate2993
This forum isn't exactly meant for homework, but its an interesting subject so I want to inject some code, and see if we can get some people to show their interesting ways to do this.
*** Source Snippet Removed ***
No biggy of course, everyone should be able to do this. So, now lets see some impressive methods.
Quote:Original post by Dave Hunt
It would appear that you are the only one who considered the possibility of negative numbers.
if (n<0) n= -n;
part isn't needed.
count = 0while 1: if n < 0: n = -n if n == 0: break n = n >> 1 count = count + 1return floor(count * 0.30103)+1
>>> def digits(n): (low, high) = (0, 9) lut = [10 ** x for x in range(1, 10)] while low != high: test = (low + high) / 2 if n < lut[test] : high = test else: low = test + 1 return low + 1# Some unit tests:>>> [digits(int('9' * n)) for n in range(1, 10)][1, 2, 3, 4, 5, 6, 7, 8, 9]>>> [digits(int('1' + '0' * n)) for n in range(1, 10)][2, 3, 4, 5, 6, 7, 8, 9, 10]>>> digits(0)1
// Assuming 32-bit integers.const int lut[9] = { 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };inline int digits(int n) { int low = 0; int high = 10; while (low != high) { int test = (low + high) / 2; if (n < lut[test]) { high = test; } else { low = test + 1; } } return low + 1;}
Quote:Original post by dohoQuote:Original post by Dave Hunt
It would appear that you are the only one who considered the possibility of negative numbers.
I thought I covered that in my case. Thepart isn't needed.if (n<0) n= -n;
int numDigits(int n){ for(int i=1,int numDigits=0;;i>n?(return numDigits):(numDigits++,i*=10)); //buggy! return -1;}
Quote:Original post by Sagar_Indurkhya
sleepy right now, but here is something:
*** Source Snippet Removed ***
It prolly has some dumb bug as usual, but I will try it later tomorrow.
Quote:Original post by Inmate2993Quote:Original post by Sagar_Indurkhya
sleepy right now, but here is something:
*** Source Snippet Removed ***
It prolly has some dumb bug as usual, but I will try it later tomorrow.
I like this one. Scoping rules probably wouldn't cause a collision with numDigits identifier, but just to be safe I'd recommend never doing that ever again. =D