Skip to content

Commit 56c02be

Browse files
committed
feat: number-of-1-bits
1 parent 9c6ca65 commit 56c02be

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

bin.number-of-1-bits.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution:
2+
"""
3+
191. 位1的个数
4+
https://leetcode-cn.com/problems/number-of-1-bits/
5+
编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 '1' 的个数(也被称为汉明重量)。
6+
"""
7+
def hammingWeight(self, n: int) -> int:
8+
count = 0
9+
while n:
10+
n = n & (n - 1)
11+
count += 1
12+
13+
return count
14+
15+
16+
so = Solution()
17+
print(so.hammingWeight(0o11111111111111111111111111111101))

pointer.remove-element.py

+3
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,13 @@ class Solution:
1010
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
1111
"""
1212
def removeElement(self, nums: List[int], val: int) -> int:
13+
# 定义快指针:标识循环元素的位置
1314
a = 0
15+
# 定义慢指针:标识非 val 值的元素位置
1416
b = 0
1517

1618
while a < len(nums):
19+
# 如果非 val,则进行赋值
1720
if nums[a] != val:
1821
nums[b] = nums[a]
1922
b += 1

0 commit comments

Comments
 (0)