# Total Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Now your job is to find the total Hamming distance between all pairs of the given numbers.

Example:

`Input: 4, 14, 2 Output: 6 Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). So the answer will be: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. `

Note:

1. Elements of the given array are in the range of `0 `to `10^9`
2. Length of the array will not exceed `10^4`.

# Using bit manipulation to achieve operators

1）计算负数的逆元

```def negative(n):

2）加法计算

```def bit_add(a, b):
b &= (2 ** 32 - 1)
while b:
tmp = a
sum = tmp ^ b
carry = (tmp & b) << 1
return a```

3）减法计算

```def bit_sub(a, b):

4）乘法计算

```def bit_mul(a, b):
result = 0

while b:
if b & 0x1:
b >>= 1
a <<= 1

return result```

5）除法计算

```def bit_div(x, y):
result = 0
for i in range(32)[::-1]:
if (x >> i) >= y:
result += (1 << i)
x -= (y << i)

return result```

I’m going to simulate the whole adding process by bit manipulation:

```def add(sum, carry):
if not carry:
return sum

sum = sum ^ carry           # Just add without carry
carry = (sum & carry) << 1  # Just carry without add

a,b = 1,1

and it works 🙂

## 我想试一试

### Status Listensmileagree, and then do whatever the fuck you were gonna do anyway.

# Find medians from a slide window

`a = [1,2,3,12,-5,33]k = 3b = [2,3,3,12]b`

# Maximum XOR of Two Numbers in an Array

Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.

Find the maximum result of ai XOR aj, where 0 ≤ ij < n.

Could you do this in O(n) runtime?

Example:

`Input: [3, 10, 5, 25, 2, 8] Output: 28 Explanation: The maximum result is 5 ^ 25 = 28.`

result += any(result ^ 1 ^ p in prefixes for p in prefixes)

```class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
result = 0

for i in range(32)[::-1]:
result <<= 1
prefixes = {num >> i for num in nums}
result += any(result ^ 1 ^ p in prefixes for p in prefixes)

return result```