leetcode

Single Number II

Given an array of integers, every element appears three times except for one. Find that single one.

The idea is count how many times that digit appears in the i's bit and get times mod 3 then assign it to the i's bit.

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