1. 位运算基础
按位运算符是把数字看作二进制来进行计算的。
1.1 基本表达
a与b: a&b
a或b: a|b
a异或b: a^b
非a: ~a
左移: <<
右移:>>
1.2 进制转换
二进制转十进制:
>>> int('1101',2)
13
>>> int('0o226',8) #00226 0:阿拉伯数字零 o:小写英文字母 o 226:八进制数
150
>>> int('0x96',16)
150
十进制转二进制:
>>> bin(13)
'0b1101'
八进制与十六进制互转:
>>> oct(0x37)
'0o67'
>>> hex(0o67)
'0x37'
2. 题目
2.1 5649. 解码异或后的数组
这个题目考查异或相关的知识
a^b=c 能推出
c^b =a
class Solution:
def decode(self, encoded: List[int], first: int) -> List[int]:
res = [first]
for i in range(len(encoded)):
temp = first^encoded[i]
res.append(temp)
first = temp
return res
2.2 5642. 大餐计数
这个题目有两个个重要的信息:
- 0 < = d e l i c i o u s n e s s [ i ] < = 2 20 0<=deliciousness[i]<=2^{20} 0<=deliciousness[i]<=220 ;也就是两个大餐之和最多为 2 21 2^{21} 221
-
1
<
<
i
1<<i
1<<i 表示
2
i
2^i
2i
解法:
将问题转为,两数之和,target为 2 n 2^n 2n, 其中 1 < n < = 21 1<n<=21 1<n<=21
import collections
class Solution:
def countPairs(self, deliciousness: List[int]) -> int:
count = 0
mod = 10**9+7
for i in range(22):
temp = 1<<i
dicta = collections.defaultdict(lambda:0)
for i, num in enumerate(deliciousness):
if temp - num in dicta:
count +=dicta[temp - num]%mod
dicta [num] += 1
return count%mod
3. 参考链接:
https://www.cnblogs.com/gkx0731/p/9501276.html