function to count the number of "1" of one byte ,for example 5(0101)has two "1"
经常遇到的面试题,毫无疑问需要借助位操作:
unsigned int bitCount (unsigned int value) {
unsigned int count = 0;
while (value > 0) { // until all bits are zero
//if ((value & 1) == 1) // check lower bit
// count++;
count += value & 0x1;
value >>= 1; // shift bits, removing lower bit
//printf("value:%d, count:%d\n", value, count);
}
return count;
}