count_set_bits

=Count the number of set bits in an int= code format="c" int count_set_bits(int x) { int total = 0; while (x) { total += x & 0x1; x >>= 1; }   return total; }

code This code hovers between being clever and elegant and being too unintuitive. Here are the parts:
 * 1) We test to see if there are //any// bits set in x in our while loop. If x is 0, our loop will never iterate even one. If x is 3, our loop will only iterate twice.
 * 2) We mask out all but the last bit (& 0x1) and add the value---which has to be either 0 (if it's unset) or 1 (if it's set)---to total
 * 3) We right-shift x by 1, getting rid of the least significant bit and moving all the others down 1
 * 4) Since right-shifts shift 0s in, we're guaranteed to eventually get 0, and the loop will end.