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?
public class Solution {
public int singleNumber(int[] A) {
int once = 0;
int twice = 0;
for (int i = 0; i < A.length; i++) {
//twice记录数位出现两次以上的情况。once记录了在A[i]之前出现的数位模3余1的情况。和当前数位与,如果为1则这个数位出现了两次。
twice |= once & A[i];
once ^= A[i];//once记录了在A[i]之前出现的数位为1的情况。
int not_three = ~(once & twice);
once = not_three & once;
twice = not_three & twice;
}
return once;
}
}