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?
解题思路:一个integer最多32位,那我们就设一个32位的数组,对于每一个数字以二进制形式加到这个数组上。最后扫描32位数组一遍%3,余数就是single number。
public int singleNumber(int[] A) {
int[] digits = new int[32];
for (int i = 0; i < 32; i++) {
for (int j = 0; j < A.length; j++) {
digits[i] += (A[j] >> i) & 1;
}
}
int result = 0;
for (int i = 0; i < 32; i++) {
result += (digits[i]%3) * (1<<i);
}
return result;
}