2917. Find the K-or of an Array

T: O(n*32) , 32 is 32 bits
S: O(32) 
```java
class Solution {
    public int findKOr(int[] nums, int k) { 
        int[] bitCount = new int[32];
        for (int num : nums) {
            int idx = 0; // accumulate for each num's bits count
            while (num > 0) {
                if ((num & 1) == 1) { // (1 is ...00000001)
                    bitCount[idx]++;
                }
                idx++;
                num = num >> 1; // check each bits in num, if it's 1, bitCount[idx]++
            }
        }
        int result = 0;
        for (int i = 0 ; i < 31; i++) {
            if (bitCount[i] >= k) { 
                result += (1 << i); // at last add pow(2, i) to result (if it's count >= k)
            }
        }
        return result;
    }
}

/**
using right shift 

& 1 -> is means AND onlylowest bit 1
(1 is ...00000001)

for each num
   each num bits
      AND 1 -> if it's 1 -> bitCount[i]++
      do num right shift at last -> num will become 0

left shift
 

T: O(n*32) , 32 is 32 bits
S: O(32) 
*/
```

better one

T: O(n*32) , 32 is 32 bits
S: O(32) 
```java
class Solution {
    public int findKOr(int[] nums, int k) { 
        int[] bitCount = new int[32];
        int result = 0;
        for (int num : nums) {
            for (int i = 0; i < 31; i++) {
                if ((num & (1 << i)) != 0) {
                    bitCount[i]++;
                    if (bitCount[i] == k) {
                        result += (1 << i);
                    }
                }
            }
        }
        return result;
    }
}

/**
if ((num & (1 << i)) != 0) {

or just untilize 
num & (1 << i) -> to check certain bits is 1 or 0 -> 
ex:
0011000
0001000 -> if result != 0 -> bits 3 is 1 (like using mask!)

so that bitCount[i]++;, once if (bitCount[i] == k) => we can add to result (result += (1 << i))

T: O(n*32) , 32 is 32 bits
S: O(32) 
*/
```

Last updated