diff --git a/算法思维系列/常用的位操作.md b/算法思维系列/常用的位操作.md index f5b5771..98f3e4b 100644 --- a/算法思维系列/常用的位操作.md +++ b/算法思维系列/常用的位操作.md @@ -172,4 +172,25 @@ http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel

-======其他语言代码====== \ No newline at end of file +======其他语言代码====== + +由[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 + ```