This is an interview question I had at Microsoft, from when I was interviewing for my very first internship. That would have been way back in early 1996.
“You are given an integer n, and you need to write a function to count how many bits in n are set to 1.”
As most reasonably savvy programmers would do, I wrote a function that shifts n to the right, counting the times that the least-significant bit is set to 1, until n is 0. Something like this:
int countBits(int n) {
int count = 0;
while (n != 0) {
if (n & 1)
count++;
n = n >> 1;
}
return count;
}
In general, this function will take O(b) time to complete, where b is the bit-width of n. This is fine; it’s a constant, so we are all happy with that.
But it turns out that there’s a faster way!
Question 1: Do you know what the faster way is?
Question 2: Do you know how it works?
I will admit up front that my interviewer showed me, way back in 1996, the faster way. But I just figured out how it works this weekend.
(more…)