非零比特的个数 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.
- 非零比特的个数 count the number of bits
- Count the number of bits that are on in an unsigned integer(计算一个无符整数中1Bit的个数)-- (1)
- Number of 1 Bits 数字二进制中1的个数
- 191. Number of 1 Bits&二进制中1的个数
- Number of 1 Bits(二进制中1的个数)
- Number of 1 Bits(二进制中1的个数)
- LeetCode 191 Number of 1 Bits(1 比特的数字们)
- [LeetCode] 零的个数 number of trailing zeros
- LeetCode 191. Number of 1 Bits(比特数)
- 三角形的数目 Count the number of possible triangles
- LeetCode OJ 之 Number of 1 Bits (二进制位1的个数)
- leetcode 191. Number of 1 Bits(1的个数)(C++和Java)(无符号位)
- Leetcode:191. Number of 1 Bits(返回一个数字对应二进制中1的个数)
- Count the number of 1(MIT hackmem)
- count the number of 2s
- leetcode:count the number of nodes
- count the number of objects--物体计数
- hnustoj 1030: Count the Number of Cycles
- php函数
- java--TCP,IP,HTTP,SOCKET区别和联系
- java--什么是Socket,为什么要用Socket
- linux c statfs系统调用
- 在Window环境下,使用CodeBlocks+GNUStep 配置Objective-C开发环境
- 非零比特的个数 count the number of bits
- 自学宝典:10个学习Android开发的网站推荐
- 黑马程序员——高新技术---Java基础-集合框架-集合Collection,List
- 十大开源ERP点评 献给深水区的中小企业和CIO们
- 加密算法之RSA
- redis中关于过期键的删除策略
- cas基础使用
- C++学习笔记——引用
- Bit-map