XOR, as the name implies, the same take 0, different take 1, XOR or operation has a binding law. There are two classic applications on the algorithm, one is to exchange two numbers, and the other is to find out the number of single-drop.
1. Exchange values for two variables
Unlike other languages, the C and C + + languages differ or do not have XOR, but instead use "^" and type as shift+6. (While the "^" in other languages generally denotes a exponentiation), if you need to exchange the values of two variables, in addition to the commonly used borrowing intermediate variables to exchange, you can also use XOR, only two variables to exchange, such as:
1 2 3 |
A=a^b; B=b^a; A=a^b; |
Detailed
1 2 3 |
A1=a^b b=a1^b a=a1^b=a1^ (a1^b) =a1^a1^b=b |
Attention:
1 |
a=a^b^ (B=a); This type of form is incorrect for UB behavior and will have different results in different compilers, do not use |
This completes the exchange of A and B. All in all: the same variable and another variable and its XOR value are different or equal to itself.
2. Single count (one drop, 2 orders):
Requires time complexity O (n), Spatial complexity O (1). To say a few words about complexity:
O (n) Such a sign is called asymptotic time complexity, which is an approximation. The order of the various asymptotic complexity from small to large is as follows
O (1) < O (Logn) < O (n) < O (Nlogn) < O (n^2) < O (n^3) < O (2^n) < O (n!) < O (n^n) The first idea is to go ahead and Traverse looking. The time complexity is O (Nlogn), and the spatial complexity is O (logn).
The second idea is to use a hash table, the time complexity is O (n), and the spatial complexity is O (n).
The third method is to use the combination of the law of the XOR operation can be, which involves the extension of the topic, if the 22 pairs of elements adjacent to the direct XOR, if it is scattered, then the first fast and then different or.