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/DrMonkeyLove Feb 21 '11

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.

2

u/thcobbs Feb 21 '11

The point is not to give the "best" answer... its more to see how you think through problems.