LeetCode 191. Number of 1 Bits
2018-03-17 00:41
423 查看
191. Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.
简而言之就是看一个无符号整数二进制数1的个数
Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.
简而言之就是看一个无符号整数二进制数1的个数
/* 二进制数借位会从最右边的1来借,如: 12 = 0000 1100, 12 - 1 = 11 = 0000 1001 0000 1100 & 0000 1001 = 0000 1000 = 8 (取掉了最右边的1) 同理: 8 = 0000 1000, 8 - 1 = 7 = 0000 0111 0000 1000 & 0000 0111 = 0000 0000 = 0 如此,我们便算出了12的二进制1的个数 */ int hammingWeight(uint32_t n) { int counter = 0; while(n){ n &= (n - 1); ++counter; } return counter; }
相关文章推荐
- LeetCode 简单操作 | 191. Number of 1 Bits
- 191. Number of 1 Bits Leetcode Python
- [leetcode]: 191. Number of 1 Bits
- [leetcode]191. Number of 1 Bits
- Leetcode:191. Number of 1 Bits(返回一个数字对应二进制中1的个数)
- LeetCode 191. Number of 1 bits (位1的数量)
- LeetCode 191. Number of 1 Bits(比特数)
- leetcode 191. Number of 1 Bits
- leetcode 191. Number of 1 Bits
- LeetCode笔记:191. Number of 1 Bits
- [leetcode] 191. Number of 1 Bits
- Leetcode 191. Number of 1 Bits
- [LeetCode]--191. Number of 1 Bits
- Leetcode 191. Number of 1 Bits (Easy) (cpp)
- LeetCode 191. Number of 1 Bits(java)
- 【LeetCode】191. Number of 1 Bits
- leetcode 191. Number of 1 Bits 数字中1的数量 + 位运算
- [LeetCode] 191. Number of 1 Bits
- LeetCode 191. Number of 1 Bits
- [LeetCode]191. Number of 1 Bits