Among the bit operators in Java, there is an operator called exclusive or. The symbol is (^) or If 1
int a=1; int b=1; System.out.println(a^b);
is different, 0
int a=12; int b=0; System.out.println(a^b);
will be output here. 12
Summary: The same two numbers will output 0, which is false, and the other number is 0, then Output itself, and the following will demonstrate two different numbers for you
Related video tutorial recommendations:
java online tutorialOperation rulesThe operation rule is: in the same bit of two binary operands
For example: a=7; b=4;
a=0111; b=0100; (because int occupies 32 bits, the first digits are all 0, so only the last 4 digits are displayed)
a^b=?
Get a^b =3
The following will explain in detail how to exchange the values in the two attributes without using a third party
What we want to achieve is a=4; b=7;
The formula is a=a^b;
b=a^b;a=a^b;
First step analysis:
The value after the first step is: a=3; b=7;
The second step: b=a^b;
Value after the second step: a=3; b=4;
The third step: a=a^b;
The value after the three steps: a=7; b=4;
The XOR operation has three characteristics. One is that 0 is XORed with a number or itself, and 0 is XORed with itself. , the XOR operation also satisfies the exchange rate.
Use the characteristics of a^a=0 to implement this function. Find the odd number of occurrences in an array, which can also be understood as the one occurrence;
The code is directly entered here;
private static void ddd() { int a[] = { 22, 38, 38,5, 22, 4, 4, 11, 11 }; int t = 0; for (int i = 0; i < a.length; i++) { t ^= a[i]; } System.out.println(t); }
This will directly output 5
The following is some basic knowledge of XOR, if you are interested, you can study it;
1. a ^ b = b ^ a
2. a ^ b ^ c = a ^ (b ^ c) = (a ^ b) ^ c;
3. d = a ^ b ^ c can be deduced that a = d ^ b ^ c.
4. a ^ b ^ a = b.
More related articles and tutorials are recommended:
java introductory learningThe above is the detailed content of In-depth understanding of XOR operator in java. For more information, please follow other related articles on the PHP Chinese website!