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?
class Solution { public: void toTribit(vector<int>& bits,int val){ if(val<0){ bits[31]=1; val=-val; } else bits[31]=0; int ind=0; while(val>0){ bits[ind]=val%3; val/=3; ind++; } for(int i=ind;i<bits.size()-1;i++)bits[i]=0; } void Xor(vector<int>& bits1,vector<int>& bits2){ for(int i=0;i<bits1.size();i++){ bits1[i]=(bits1[i]+bits2[i])%3; } } int tribitToInt(vector<int>& bits){ int ret=0; if(bits[31]==1){ for(int i=bits.size()-2;i>=0;i--){ ret*=3; ret-=bits[i]; } if(ret==0)return 0x80000000; } else{ for(int i=bits.size()-2;i>=0;i--){ ret*=3; ret+=bits[i]; } } return ret; } int singleNumber(int A[], int n) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<int> bits1,bits2; if(n<1)return 0; bits1.resize(32,0); bits2.resize(32,0); toTribit(bits1,A[0]); // cout<<tribitToInt(bits1)<<endl; for(int i=1;i<n;i++){ toTribit(bits2,A[i]); Xor(bits1,bits2); // cout<<tribitToInt(bits2)<<endl; } if(n%3==2){ for(int i=0;i<32;i++){ switch(bits1[i]){ case 0: bits1[i]=0;break; case 1:bits1[i]=2;break; case 2:bits1[i]=1;break; default:break; } } } return tribitToInt(bits1); } };