只有一个数出现一次其与数都出现三次,我们可以统计所有数用二进制表示后的每位数上的情况,将所有数的二进制表示后各位数相加;显然只有目标数涉及到的位数上的情况无法被三整除,我们找出这些位数然后就可以组合成目标数了。
class Solution {
public int singleNumber(int[] nums) {
int[] arr = new int[32];
for (int num : nums) {
int cnt = 0;
// 累加各数二进制情况
while(cnt < 32) {
if((num & 1) == 1) arr[cnt]++;
num >>= 1;
cnt++;
}
}
int ans = 0;
// 是负数我们记录的是补码形式还要再变回来
if(arr[31] % 3 != 0) {
for(int i = 0; i < 32; i++) {
if(arr[i] % 3 == 0) {
ans += Math.pow(2, i);
}
}
ans += 1;
ans *= -1;
} else {
for (int i = 0; i < 31; i++) {
if (arr[i] % 3 == 1) {
ans += Math.pow(2, i);
}
}
}
return ans;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.singleNumber(new int[]{-2,-2,1,1,4,1,4,4,-4,-2}));
}
}
1674

被折叠的 条评论
为什么被折叠?



