Single Number II
Given an array of integers, every element appears three times except for one.
Find that single one.
Your algorithm should have a linear runtime complexity. Could you implement it
without using extra memory?
Solution: Count the number of each bit.
1 class Solution { 2 public: 3 // assume that integers are 32bits 4 int singleNumber(int A[], int n) { 5 int res = 0; 6 for(int i = 0; i < 32; i++) { 7 int count = 0; 8 int bit = 1 << i; 9 for(int j = 0; j < n; j++) { 10 if(A[j] & bit) { 11 count++; 12 } 13 } 14 if(count % 3) { 15 res = res | bit; 16 } 17 } 18 return res; 19 } 20 };