mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-05 03:36:39 +08:00
Update 常用的位操作.md
位1的个数python3
This commit is contained in:
@ -173,3 +173,26 @@ http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
|
||||
</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
|
||||
|
||||
'''
|
||||
|
Reference in New Issue
Block a user