题目:
思路+代码:
class Solution:
def singleNumber(self, nums: List[int]) -> int:
# 遍历求和每个数字32位,然后对每一位对3进行取余留下了的数字便只留下出现一次的数
if not nums:
return
count = [0] * 32
for num in nums:
for i in range(32):
count[i] += 1 & num # 判断每一位是否是1
num >>= 1
res, m = 0, 3
for j in range(32):
res <<= 1 # 0按位左移仍然是0
res |= count[31-j] % m
return res if count[31] % m == 0 else ~(res ^ 0xffffffff)
位运算:
- 异或运算:
x ^ 0 = x
,x ^ 1 = ~x
- 与运算:
x & 0 = 0
,x & 1 = x