LeetCode 191. Number of 1 Bits (Easy)
2017-11-15 13:15
387 查看
题目描述:
Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).Example:
The 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
题目大意:找出一个无符号整数的二进制形式的1的个数。
思路:直接做也不是不可以(循环找1)。但是我从网上看到了一个很巧妙的方法:当n不等于0时,n = n & (n - 1),循环次数就是1的个数。思考了一下:n & n - 1可以令最低位的1消掉,所以每一次消除一个最低位的1,消除的次数就是1的个数了。以题目为例:
n | n-1 | n & n - 1 |
---|---|---|
00000000000000000000000000001011 | 00000000000000000000000000001010 | 00000000000000000000000000001010 |
00000000000000000000000000001010 | 00000000000000000000000000001001 | 00000000000000000000000000001000 |
00000000000000000000000000001000 | 00000000000000000000000000000111 | 00000000000000000000000000000000 |
class Solution { public: int hammingWeight(uint32_t n) { int ans = 0; while (n) { n = n & (n - 1); ans++; } return ans; } };
相关文章推荐
- Leetcode 191. Number of 1 Bits (Easy) (cpp)
- 【leetcode】191. Number of 1 Bits(easy)
- 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
- LeetCode191. Number of 1 Bits
- leetcode 191. Number of 1 Bits
- (easy)LeetCode 191.Number of 1 Bits
- Leetcode 191. Number of 1 Bits
- LeetCode 191. Number of 1 Bits
- leetcode_Number of 1 Bits_easy
- LeetCode 191. Number of 1 Bits
- 【Leetcode】Number of 1 Bits(easy)
- 【leetcode】191. Number of 1 Bits 关于位运算的几个小技巧。191. Number of 1 Bits()
- [leetcode]: 191. Number of 1 Bits
- LeetCode-191. Number of 1 Bits
- 191. Number of 1 Bits Leetcode Python
- leetcode 191. Number of 1 Bits