English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In Java's bitwise operators, there is an operator called XOR, represented by the symbol (^), and its operation rule is: if the bits of the two operands are the same, the result is 0, and if they are different, the result is1. Let's look at an example:
public class TestXOR{ public static void main(String[] args){ int i = 15, j = 2; System.out.println("i ^ j = ") + (i ^ j)); } }
The running result is: i ^ j=13.
Analysis of the above program, i=15, converted to binary is1111, j=2, converted to binary is 0010, according to the operation rules of XOR, we get1101, converted to decimal is13.
Using this rule, we can flexibly apply it to some algorithms. For example, assuming there is2K+1number of, there are2k identical, we need to find the number that is different, for example:2,3,4,4,3,5,6,6,5. We can write it like this using the XOR operator:
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 appears only once is: ") + v); } }
The result is: the number that appears only once is2.
We take advantage of the rules of the XOR operator to deduce that a number XORed with 0 is itself, and a number XORed with itself is 0.
The above calculation method: v=2^3^4^4^3^5^6^6^5;
According to the commutative law and the above rules
We can deduce the number that appears only once (under the premise condition)2k identical)
Summary
That is all the code analysis of the XOR problem in Java. I hope it is helpful to everyone. Those who are interested can continue to read other related topics on this site, and welcome to leave comments if there are any shortcomings. Thank you for your support to this site!
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)