topic:
Thought:
- firstBit operation有三个特性:
- Any number and0Different or operational,The result is still the original number,Right now a XOR 0 = a。
- Any number and自身Different or operational,turn out0,Right now a XOR a = 0。
- Different or operations meet the law of exchange and binding。first,We need to calculate the array nums All elements of all elements,Be remembered xor_sum。Our goal is to make some positions to make xor_sum equal k。
1
2
3
4
5a = 0b1001
b = 0b0110
bin(a ^ b)
'0b1111'
then,We can consider xor_sum XOR k the result of。Due to the characteristics of different or computing,The difference in any position will cause the bit in the result to be1。this means,We need to change xor_sum and k All different places in binary representation。
if xor_sum = 1010,k = 0011,So xor_sum XOR k = 1001。We need to change第一位and第四位来让 xor_sum become k。
That is numsHeterogeneity
and k
Value, in1The number is the number that needs to be converted。can watch0x3fSolution
Code:
1 | class Solution: |
1 | func minOperations(nums []int, k int) int { |