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.
3 ms
class Solution {
public:
int hammingWeight(uint32_t n) {
int ans = 0;
while(n) {
if (n & 1) ans++;
n >>= 1;
}
return ans;
}
};
better;
"n &= n - 1" is used to delete the right "1" of n. For example:
- if n = 5 (101), then n-1 = 100, so n & (n-1) = 100, the right "1" is deleted;
- if n = 6,(110), then n-1 = 101, so n & (n-1) = 100, the right "1" is also deleted;
- and so on...
So time complexity is O(m), and m is the count of 1's, also m is less than or equal to 32.
class Solution {
public:
int hammingWeight(uint32_t n) {
int ans = 0;
while(n) {
n &= n-1;
++ans;
}
return ans;
}
};
本文介绍了一种高效的方法来计算一个给定的32位无符号整数在其二进制表示中1的个数,即汉明重量。通过两种不同的算法实现:逐位检查和清除最低位的1,后者的时间复杂度为O(m),其中m为1的个数。
523

被折叠的 条评论
为什么被折叠?



