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?
思路:之前single number那个题是 every element appears twice except for one,那个是异或即可
出现三次的话,把每个数看做二进制,每个位置上的0/1相加,然后对三取模,所的得即是最后结果的那位数字。
class Solution {
public:
int singleNumber(int A[], int n) {
int bin[32] = {0};
int ans = 0;
for(int i = 0; i < 32 ; i++){
for(int j = 0 ; j < n ; j++){
bin[i]+=(A[j]>>i)&1; //判断第i位 是否为1
}
ans|=(bin[i]%3)<<i; //<<即相当于乘以加权数,*2,*2^2, *2^3 ...
}
return ans;
}
};