Title: Given An array of integers, every element appears twice except for one. Find the single one.
Note: This array is not said to be in a fixed order
Idea: Import java.util.Arrays;
public class Singlenum {
public int singlenumber (int[] nums) {
int r = 0;
for (int x:nums) {
r = r ^ x; Here is the use of the XOR operation, which has two large characteristics: 1, a=0^a;
//2, a^b = B^a; Meet the Exchange law, then in the chaotic Order (1,2,3,4,3,2,1),
//Can be its first (1,1,2,2,3,3,4), then use the nature to do, return is;
}
return R;
}
}
When doing the problem, by the way Java's bitwise arithmetic logic to learn a bit, very feeling. It is summarized as follows:
1, XOR or operation: A^b, "The same is 0, the difference is 1".
Properties:
(1) The location of the a,b,p here is interchangeable !!! (same or also can)
(2) If you need to exchange the values of two variables, in addition to the usual use of the borrowed intermediate variables to exchange, you can also use XOR, only two variables to exchange , such as:a=a^b; b=b^a; a=a^b;(好用!)
(3) a:a^0 =a;
B:a ^b ^c = a ^ (b ^ c) = (a ^ b) ^ C; (Binding law)
c:a ^ b ^ a = b; (Transform position)
D:d = a ^ b^ C can be introduced a = d ^ b ^ C;
2, the same or operation (XOR non):! (a^b), "Same as 1, different for 0"
3, and (in series): A&&b,
4, or (parallel): a| | B
5, non (NO):!a,
Leetcode--single number