非零比特的个数 count the number of bits

来源:互联网 发布:淘宝女装一件代发 编辑:程序博客网 时间:2024/05/13 01:10

Counting bits set, Brian Kernighan's way

unsigned int v; // count the number of bits set in vunsigned int c; // c accumulates the total bits set in vfor (c = 0; v; c++){  v &= v - 1; // clear the least significant bit set}

Brian Kernighan's method goes through as many iterations as there are set bits. So if we have a 32-bit word with only the high bit set, then it will only go once through the loop.


例如:

128 == 100000002, 1 bit set

128 & 127 ==   0    10000000 & 01111111 == 00000000

177 == 101100012, 4 bits set

177 & 176 == 176    10110001 & 10110000 == 10110000176 & 175 == 160    10110000 & 10101111 == 10100000160 & 159 == 128    10100000 & 10011111 == 10000000128 & 127 ==   0    10000000 & 01111111 == 00000000

255 == 111111112, 8 bits set

255 & 254 == 254    11111111 & 11111110 == 11111110254 & 253 == 252    11111110 & 11111101 == 11111100252 & 251 == 248    11111100 & 11111011 == 11111000248 & 247 == 240    11111000 & 11110111 == 11110000240 & 239 == 224    11110000 & 11101111 == 11100000224 & 223 == 192    11100000 & 11011111 == 11000000192 & 191 == 128    11000000 & 10111111 == 10000000128 & 127 ==   0    10000000 & 01111111 == 00000000

As for the language agnostic question of algorithmic complexity, it is not possible to do better than O(n) where n is the number of bits. Any algorithm must examine all of the bits in a number.

What's tricky about this is when you aren't careful about the definition of n and let n be "the number of bit shifting/masking instructions" or some such. If n is the number of bits then even a simple bit mask (&) is already an O(n) operation.

So, can this be done in better than O(n) bit tests? No.
Can it be done in fewer than O(n) add/shift/mask operations? Yes.




0 0
原创粉丝点击