day8-位运算
1. 剑指 Offer 15. 二进制中1的个数
1 | class Solution: |
1
2
3
4
5
6
7class Solution:
def hammingWeight2(self, n: int) -> int:
res = 0
while n:
res+=1
n&=(n-1)
return res
2. 剑指 Offer 16. 数值的整数次方
1 | class Solution: |
3. 剑指 Offer 56 - I. 数组中数字出现的次数
1
2
3
4
5
6
7
8
9
10
11class Solution:
def singleNumbers(self, nums: List[int]) -> List[int]:
x, y, n, m = 0, 0, 0, 1
for num in nums: # 1. 遍历异或
n ^= num
while n & m == 0: # 2. 循环左移,计算 m
m <<= 1
for num in nums: # 3. 遍历 nums 分组
if num & m: x ^= num # 4. 当 num & m != 0
else: y ^= num # 4. 当 num & m == 0
return x, y # 5. 返回出现一次的数字
4. 剑指 Offer 65. 不用加减乘除做加法
1 | class Solution: |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 yelin!