尋找出兩個出現奇數次的整數

來源:程序員小灰

預備知識:

按位 與 運算:
0 & 0=0
0 & 1=0
1 & 0=0
1 & 1=1
按位 異或 運算:
0 ^ 1 = 1
1 ^ 1 = 0
0 ^ 0 = 0
1 ^ 0 = 1
package chapter5.part12;

import org.junit.Test;

public class FindLostNumTest {
	
	@Test
	public void findLostNumTest() {
		int[] array = {4,1,2,2,5,1,4,3};
        int[] result = findLostNum(array);
        System.out.println(result[0] + "," + result[1]);
	}

	private int[] findLostNum(int[] array) {
		int[] result = new int[2];
		//第一次整體異或運算
		int xorResult = 0;
		for (int i=0; i<array.length; i++) {
			xorResult ^= array[i];
		}
		//如果整體運算結果爲0,說明不存在兩個出現奇數次的整數
		if (xorResult == 0) {
			return null;
		}
		//找到倒數的第1個1
		int cut = 1;
		while (0 == (xorResult&cut)) {
			cut <<= 1;//左移
		}
		for (int i=0; i<array.length; i++) {
			boolean ifZero = (0 == (array[i]&cut));
			if (ifZero) {
				result[0] ^= array[i];
			} else {
				result[1] ^= array[i];
			}
		}
		return result;
	}

}

測試結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章