Q:
Given an array of integers, every element appears twice except for one. Find that single one.
Note:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
A:
public int singleNumber(int[] A) {
int x = 0;
for (int i : A) { //遍歷數(shù)組A,每次把讀的數(shù)字放入i中
x = x ^ i;
}
return x;
}
Bit manipulation,比較的是bit位,一樣的話返回0,不一樣返回1。沒有搜索的必要了。
比如 int[] A = {1, 2, 3, 2, 3, 4, 1};
x = x ^ 1; // 0000^0001 = 0001, x=1
x = 1 ^ 2; // 0001^0010 = 0011, x=3
x = 3 ^ 3; // 0011^0011 = 0000, x=0
x = 0 ^ 2; // 0000^0010 = 0010, x=2
x = 2 ^ 3; // 0010^0011 = 0001, x=1
x = 1 ^ 4; // 0001^0100 = 0101, x=5
x = 5 ^ 1; // 0101^0001 = 0100, x=4
return 4
突然還想到了之前某筆試題里同XOR一起出現(xiàn)的運算符,邏輯左移:>>
-
重載輸出流運算符,一般運用格式為:
cout<<x;其中cout為流文件,如顯示設備、輸出設備、或者數(shù)據(jù)文件等。(僅C++中) -
數(shù)據(jù)移位運算符,左移幾位,如:
x=i<<4;就是將i的值左移4位(放大2的4此方)后,賦給x,若i=2, 則X=32, 0000 0000 0010 0000 ,這里簡單地一個二進制轉(zhuǎn)十進制,1 x 2^6