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?
这道题也是使用位运算,但由于三位已经不能用异或自己抵消了,所以可以考虑采用所有数相加然后按位mod3,不用考虑进位问题,因为只有一个数是只出现一次,其他都是三次,每个数的二进制每一位相加mod3都不会超过1,因为3个相同的mod3一定为0,这样就不影响单独的那个数在该位上的显示。最后再将各个位组合在一起就形成了这个单独的数字。
注:一定要注意运算符优先级问题,之前就因为弄不清优先级又没加括号区分,输出的数字不是数组里数字的情况。
Source
public class Solution {
public int singleNumber(int[] A) { //遇到多个运算符时记不清楚优先级时一定要多加些括号
if(A.length == 0) return 0;
int[] bit = new int[32];
int a = 0;
for(int i = 0; i < 32; i++){
for(int j = 0; j < A.length; j++){
bit[i] = bit[i] + ((A[j]>>i) & 1); //&优先级高于>> >>i将十进制数右移到要取的那一位为最低位 &1取出最低位
}
a = a | ((bit[i] % 3) << i); //<<再左移回来 |用于合并各个位
}
return a;
}
}
Test
public static void main(String[] args){
int[] A = {2,2,2,3,4,3,3};
System.out.print(new Solution().singleNumber(A));
}