leetcode解题: Number of 1 Bits (191)

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:O(M) M is number of total set bits

运用n & (n -1)消掉最高位的set bit的思想,可以不停重复这个操作直到n变为0,
这样的复杂度可以减少为所有1的个数
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int hammingWeight(uint32_t n) {
if (n == 0) {
return 0;
}
int count = 0;
while (n != 0) {
++count;
n = n & (n - 1);
}
return count;
}
};

解法2:O(N) N is number of total bits

用右移的方法来判断每一位是否是1直到n变为0
C++

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
while (n != 0) {
res += n & 1;
n = n >> 1;
}
return res;
}
};

Java

1