位1的个数(算法)
题目: 位1的个数
编写一个函数, 输入是一个无符号整数,
返回其二进制表达式中数字位为1的个数
3: 011 -> 2
5: 101 -> 2
8: 1000 -> 1
1.x % 2 ? 1 -> count++; x = x >> 1; 2.x = x & (x - 1) 11000 = 24 x = 11000 x - 1 = 10111
=> 10000
while x
!= 0:
count
++
x
= x
& (x
- 1)
python
def hamingWeight(self
, n
):
rst
= 0
mask
= 1
for i
in range(32):
if n
& mask
:
rst
+= 1
mask
= mask
<< 1
return rst
java
int hammingWeight(uint32_t n
) {
int res
= 0;
for (; n
; n
&= n
- 1)
++ res
;
return res
;
}