Number of 1 Bits


According to https://graphics.stanford.edu/..., the earliest publication of the 2nd method is due to Peter Wegner (from CACM 3 [1960], p.322). Also discovered independently by Derrick Lehmer and published in 1964.
The Control Data 6000/7000 series machines (with their 60bit words and 1scomplement arithmetic) had an instruction to count bits set that they called "population count."

There is an even easier bitwise trick which is constant time:
int hammingWeight(uint32_t n)
{
n = (n & 0x55555555) + ((n >> 1) & 0x55555555);
n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f);
n = (n & 0x00ff00ff) + ((n >> 8) & 0x00ff00ff);
n = (n & 0x0000ffff) + ((n >> 16) & 0x0000ffff);
return (n);
}

@Eroica I agree about the readability, but the improvement on runtime could be noticed if this function would be applied to lots of integers with only a few bits set. It`s a specific case, but maybe worth mentioning in an interview.