# leetcode top100 刷题(位运算)

## 78. 子集

[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]]

class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
powerset = []
for i in range(pow(2, len(nums))):
b = list(bin(i)[2:])
b.reverse()
while len(b) < len(nums):
b.append('0')
b.reverse()
subset = []
for i in range(len(nums)):
if (b[i] == '1'):
subset.append(nums[i])
powerset.append(subset)
return(powerset)

class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
powerset = []
for i in range(2**len(nums)):
sebset = []
for j in range(len(nums)):
if i >> j & 1:
subset.append(nums[j])
powerset.append(subset)
return res

i >> j & 1

>>> [[2]]+[[3]]

[[2],[3]]

class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
powerset = [[]]
for num in nums:
powerset = powerset + [[num]+j for j in powerset]
return(powerset)

## 136. 只出现一次的数字

A B $$A⊕B$$
0 0 0
0 1 1
1 0 1
1 1 0

class Solution:
def singleNumber(self, nums: List[int]) -> int:
a = 0
for i in nums:
a = a^i
return(a)

nums = [1,2,3,1]
print(set(nums))
>>> {1, 2, 3}

class Solution:
def singleNumber(self, nums: List[int]) -> int:
return(2*sum(set(nums))-sum(nums))

## 169. 多数元素

class Solution:
def majorityElement(self, nums: List[int]) -> int:
dic = {}
for i in nums:
if i not in dic:
dic[i] = 1
else:
dic[i] += 1
max = 0
num = 0
for key in dic:
if dic[key]>max:
max = dic[key]
num = key
return(num)

class Solution:
def majorityElement(self, nums):
counts = collections.Counter(nums)
return max(counts.keys(), key=counts.get)

import collections
num = [1,2,3,4,5,6,1,2,3]
dic  = collections.Counter(num)
print(dic)
type(dic)

Counter({1: 2, 2: 2, 3: 2, 4: 1, 5: 1, 6: 1})
collections.Counter

max(dic.keys(), key=dic.get)

max(dic, key=dic.get)

1

class Solution:
def majorityElement(self, nums: List[int]) -> int:
dic = collections.Counter(nums)
return(max(dic,key = dic.get))

## 338. 比特位运算

class Solution:
def countBits(self, num: int) -> List[int]:
return([sum(1 for q in str(bin(i)) if q == '1') for i in range(num + 1)])

## 461.汉明距离

0 ≤ x, y < 231.

1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑

class Solution:
def hammingDistance(self, x: int, y: int) -> int:
return(sum(1 for i in range(len(str(bin(x^y)))) if (x^y)>>i & 1 == 1))

'asdasdadfasds'.count('a')

4

return(bin(x^y).count('1'))