leetcode-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.

分析


常规题目,不过能学到一种bit操作的技巧,运算 n &= n-1 让 n 的最低位1反转,最后记录操作的次数即可。

解决方案1(Python)


常规做法,循环检查二进制位。

1
2
3
4
class Solution:
def hammingWeight(self, n: int) -> int:
result = sum(1 for i in range(32) if n & (1 << i))
return result

解决方案2(Python)


优化后的位运算。

1
2
3
4
5
6
7
class Solution:
def hammingWeight(self, n: int) -> int:
result = 0
while n:
n &= n-1
result += 1
return result

解决方案3(C++)


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

一种bit操作的技巧。。。。每次运算 n &= n-1 让 n 的最低位1反转。

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

解决方案4(Golang)


1
2
3
4
5
6
7
8
9
10
func hammingWeight(num uint32) int {
result := 0
var i uint32 = 0
for ; i < 32; i++ {
if 1 << i & num > 0 {
result++
}
}
return result
}

相关问题


题目来源