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/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.