【191. 位1的个数】【Python3】

【191. 位1的个数】【Python3】
This commit is contained in:
BruceCat
2021-03-15 15:10:25 +08:00
committed by GitHub

View File

@ -173,3 +173,24 @@ http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
</p>
======其他语言代码======
由[JodyZ0203](https://github.com/JodyZ0203)提供 191. 位1的个数 Python3 解法代码:
```Python
class Solution:
def hammingWeight(self, n: int) -> int:
# 先定义一个count用来存1的出现数量
count = 0
# 只要二进制串不等于0之前我们用一个循环边消除1和计1的出现数量
while n!=0:
# 用labuladong在文章中所提到的 n&(n-1) 技巧来消除最后一个1
n = n & (n-1)
count+=1
# 当二进制串全消除完之后返回1出现的总数量
return count
```