今天面試的時候被問到了一個算法題,題目如下:
在一個所有數字都出現偶數次的數組中,去掉其中一個數字,如何找出這個數字。
這道題就用到了運算符。
下面先簡單介紹一下三個運算符,如下代碼:
private static int a = 5; // 0101
private static int b = 11; // 1011
private static void testAB() {
System.out.println(a|b); // 1111 15
System.out.println(a^b); // 1110 14
System.out.println(a&b); // 0001 1
}
進行按位運算,算是複習了一下知識。
然後特殊的記錄一下“ ^ ”的知識點:
自己與自己異或爲0;
具有傳遞性;
00->0;
01->1;
11->0;
現在解答一下上面提到的面試題:
private static int result = 0;
private static int[] arrs = {1,2,1,2,6,7,8,4,121,4,5,6,7,8,5};
public static void main(String[] args) {
getResult();
}
private static void getResult() {
for(int i = 0; i < arrs.length; i ++) {
result ^= arrs[i];
}
System.out.println(result);
}
就是隻用了異或運算。
最後貼出本章的整體代碼
public class TestAlgorithm {
private static int result = 0;
private static int[] arrs = {1,2,1,2,6,7,8,4,121,4,5,6,7,8,5};
public static void main(String[] args) {
getResult();
testAB();
}
private static void getResult() {
for(int i = 0; i < arrs.length; i ++) {
result ^= arrs[i];
}
System.out.println(result);
}
private static int a = 5; // 0101
private static int b = 11; // 1011
private static void testAB() {
System.out.println(a|b); // 1111 15
System.out.println(a^b); // 1110 14
System.out.println(a&b); // 0001 1
}}