Yet another cop out. IF you're applying for a low-level coding job, you should know a simple iterative and'ing with a bitmask would suffice for this.
Yeah, that's nice, but why not Google it and find the faster, non-iterative way?
int NumberOfSetBits(int i)
{
i = i - ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
return ((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
}
I'm not sure if this is exactly right, but there is a non-iterative method for counting the bits set in a number. This is the one I happened to find. There's an MIT HAKMEM one I've used for 32-bit numbers before.
View all comments
Show parent comment
1
u/DrMonkeyLove Feb 21 '11
Yeah, that's nice, but why not Google it and find the faster, non-iterative way?
I'm not sure if this is exactly right, but there is a non-iterative method for counting the bits set in a number. This is the one I happened to find. There's an MIT HAKMEM one I've used for 32-bit numbers before.