Skip to content

Commit 2fd926b

Browse files
committed
update
1 parent 37f8e91 commit 2fd926b

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

53. 颠倒二进制位.md

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
***颠倒给定的 32 位无符号整数的二进制位。***
2+
3+
```
4+
class Solution:
5+
# @param n, an integer
6+
# @return an integer
7+
def reverseBits(self, n):
8+
res = 0
9+
for i in range(32):
10+
res = (res << 1) | (n & 1)
11+
n >>= 1
12+
return res
13+
```

54. 位1的个数.md

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
***编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 '1' 的个数(也被称为汉明重量)。***
2+
3+
```
4+
class Solution(object):
5+
def hammingWeight(self, n):
6+
res = 0
7+
while n:
8+
res += n & 1
9+
n >>= 1
10+
return res
11+
```
12+
13+
```
14+
class Solution(object):
15+
def hammingWeight(self, n):
16+
#n & (n - 1) 的技巧可以消除二进制中最后一个 1
17+
res = 0
18+
while n:
19+
res += 1
20+
n &= n - 1
21+
return res
22+
```

55. 多数元素.md

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
***给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。***
2+
3+
```
4+
class Solution:
5+
def majorityElement(self, nums: List[int]) -> int:
6+
#投票法
7+
count = 0
8+
candidate = None
9+
for num in nums:
10+
if count == 0:
11+
candidate = num
12+
if num == candidate:
13+
count += 1
14+
else:
15+
count -= 1
16+
return candidate
17+
```

0 commit comments

Comments
 (0)