Update 常用的位操作.md

位1的个数python3
This commit is contained in:
Jody Zhou
2020-11-11 20:13:30 -05:00
committed by GitHub
parent 36f59b6fe9
commit f6d6db49b5

View File

@ -172,4 +172,27 @@ http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
<img src="../pictures/qrcode.jpg" width=200 >
</p>
======其他语言代码======
======其他语言代码======
由[JodyZ203](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
'''