File tree 3 files changed +52
-0
lines changed
3 files changed +52
-0
lines changed Original file line number Diff line number Diff line change
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
+ ```
Original file line number Diff line number Diff line change
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
+ ```
Original file line number Diff line number Diff line change
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
+ ```
You can’t perform that action at this time.
0 commit comments