Bit Manipulation, work from latched
Single Number I
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?
class Solution:
# @param A, a list of integer
# @return an integer
def singleNumber(self, A):
x = 0
for numbers in A:
x=x^numbers
return x
Single Number II
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
class Solution {
public:
int singleNumber(int A[], int n) {
int oneNum = 0;
int twoNum = 0;
int threeNum = 0;
for(int i = 0 ; i < n ;i++){
threeNum = twoNum & A[i];
twoNum = oneNum & A[i] | twoNum;
oneNum = oneNum | A[i];
oneNum = oneNum &(~threeNum);
twoNum = twoNum & (~threeNum);
threeNum = 0;
}
return oneNum;
}
};
Summary : or operation to get 1, and operation to accumulate 1, and (not) to clear.
This method can be extend for more case for question like single number