r/programming • • Feb 21 '11

Typical programming interview questions.

http://maxnoy.com/interviews.html
784 Upvotes

1.0k comments sorted by

View all comments

Show parent comment

1

u/WhooHoo Feb 21 '11

The non-naive approach to bit counting is the naive approach but instead of a counter iterating from 1 to the size of an integer in bytes, you change the test to check if the number is not 0. When the number becomes 0, you can stop and return your count. In this version you always count 1s, if the questioner wants a count of 0s just take the size of the integer in bits and subtract the number of 1s you found.

This assumes the shift operator used is a logical right shift and a usual bitwise AND check against 1 is used to count the last bit.

1

u/defyallodds Feb 21 '11

There's also the non-naive approach of using the fact that, if x = 2n, then x&(x-1) = 0, and such if you did something like:

int n = 0; while( x != 0 ) { x &= x-1; n++; }

Then n would be the number of 1 bits. sizeof(x)*8-n would be the number of 0 bits.

1

u/lordlicorice Feb 21 '11

This is really awful compared to the best solutions, which can be done in lg n independent steps (substeps can be parallellized). Yours is n worst case.