A Simple Solution for All similar problems


  • 14
    R
    public class Solution {
     public int singleNumber(int[] nums) {
        int[] digit = new int[32];
        for(int i = 0; i < 32; i++){
            // for each digit, we count the number of appearance in the array
            for (int j = 0; j < nums.length; j++){
                digit[i]+= (nums[j]>>i)&1; // get the value (0 or 1) at ith digit of nums[j]
            }
        }
        int res = 0;
        for (int i =0; i< 32; i++){
            // (digit[i]%3) is mode of 3, if it is not zero, it means the single number has 1 on this digit.
            int d = digit[i]%3 ==0 ? 0: 1;
            res += (d)<<i;
        }
        return res;
    }
    

    }


  • 0
    C

    Hi, I don't understand why "digit[i]%3". Why the number has 1 on this digit if the mode of 3 is not zero? Shouldn't we mode 2?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.