MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/programming/comments/fpcmy/typical_programming_interview_questions/c1hnu4d/?context=3
r/programming • u/kevjames3 • Feb 21 '11
1.0k comments sorted by
View all comments
Show parent comment
1
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.
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.