algorithm - What is the most efficient to count trailing zeroes in an integer? -
normal way is
int main(){ int a=2000,count=0,temp; while(a!=0) { temp=a%10; if(temp==0) count++ else break; a/=10; } printf("%d",count); }
is there more efficient way ?
for 32-bit integer (maximum value 2147483647) need maximum of 4 tests. 64 bits add 1 more test 16 zeros.
start larger powers of 10 , work down:
int counttrailingzeros(int n) { int zeros = 0; if((n % 100000000) == 0) { zeros += 8; n /= 100000000; } if((n % 10000) == 0) { zeros += 4; n /= 10000; } if((n % 100) == 0) { zeros += 2; n /= 100; } if((n % 10) == 0) { zeros++; } return zeros; }
this has better worst-case performance, if 9/10ths of numbers pass have no trailing zeros average case worse. depends on values passing in typical case.
however, if 9/10ths of numbers pass have no trailing zeros shouldn't worry optimizing original code in first place since break in first iteration of loop 90% of time.
Comments
Post a Comment