本文共 804 字,大约阅读时间需要 2 分钟。
Count the number of set bits for an 32 bits integer. How to improve the process for the second time use if the memory is unlimited?
-------------------------------------------
Tricky Solution:
uint bit_count(uint value){ printf("0x%08X has ", value, value); value = (value & 0x55555555) + ((value & 0xaaaaaaaa) >> 1); value = (value & 0x33333333) + ((value & 0xcccccccc) >> 2); value = (value & 0x0F0F0F0F) + ((value & 0xF0F0F0F0) >> 4); value = (value & 0x00FF00FF) + ((value & 0xFF00FF00) >> 8); value = (value & 0x0000FFFF) + ((value & 0xFFFF0000) >> 16); printf("%d bits set.\n", value); return value;}General solution:
int count=0; while(n>0){ //n-1 will set the right most set bit to zero. AND with the same number will sustain the remaining bits n&=n-1; count++; }
转载地址:http://vwboi.baihongyu.com/