Thursday, June 12, 2014

LeetCode SingleNumberII

need a bit vector to store how many times 1 occurs on one bit.

public int singleNumber(int[] A) {
        int[] countsPerBit = new int[32];
        int result = 0;
        for (int i=0; i<32; i++) {
            for (int j=0; j<A.length; j++) {
                if ((A[j]>>i & 1) == 1) {
                    countsPerBit[i] = (countsPerBit[i] + 1)%3;
                }
            }
        result |= (countsPerBit[i] << i);
        }
        return result;
    }

No comments:

Post a Comment