今天面试的时候被问到了一个算法题,题目如下:
在一个所有数字都出现偶数次的数组中,去掉其中一个数字,如何找出这个数字。
这道题就用到了运算符。
下面先简单介绍一下三个运算符,如下代码:
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
}}