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) { //遍历数组A,每次把读的数字放入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一起出现的运算符,逻辑左移:>>
-
重载输出流运算符,一般运用格式为:
cout<<x;
其中cout为流文件,如显示设备、输出设备、或者数据文件等。(仅C++中) -
数据移位运算符,左移几位,如:
x=i<<4;
就是将i的值左移4位(放大2的4此方)后,赋给x,若i=2, 则X=32, 0000 0000 0010 0000 ,这里简单地一个二进制转十进制,1 x 2^6