There is an operator called exclusive OR in Java bit operator, which is represented by the symbol (^). The operation rules are: among the bits of two operands, the result is 0 if the result is 1 if the bits of two operands are the same, and the result is 1 if the result is different. Let's see an example below:
public class TestXOR{public static void main(String[] args){int i = 15, j = 2;System.out.println("i ^ j = " + (i ^ j));}}The operation result is: i^j=13.
Analyzing the above program, converting i=15 into binary is 1111, converting j=2 into binary is 0010, and obtaining 1101 according to the operation rules of XOR, and converting it to decimal is 13.
Using this rule, we can flexibly apply certain algorithms. For example, if there are 2K+1 numbers, and 2k of them are the same, you need to find the different numbers, such as: 2, 3, 4, 4, 3, 5, 6, 6, 5. We can use the XOR operator to write this way:
public class TestXOR{public static void main(String[] args){int[] array = {2,3,4,4,3,5,6,6,5};int v = 0;for (int i = 0;i < array.length;i++) {v ^= array[i];}System.out.println("The number that only appears once is:" + v);}}The result is: the number that only appears once is 2.
We just use the rules of the XOR operator to obtain the principle that a number and 0 are the XOR or oneself, and a number and oneself are the XOR or oneself.
The above calculation method: v=2^3^4^4^3^5^6^6^5;
According to the law of exchange and the above rules
The number that only appears once can be output (2k of the same prerequisites must be met)
Summarize
The above is all the content of this article about the code analysis of XOR problem in Java, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!