[LeetCode] Find the K-or of an Array

2917. Find the K-or of an Array

You are given a 0-indexed integer array nums, and an integer k.

The K-or of nums is a non-negative integer that satisfies the following:

  • The ith bit is set in the K-or if and only if there are at least k elements of nums in which bit i is set.

Return the K-or of nums.

Note that a bit i is set in x if (2i AND x) == 2i, where AND is the bitwise AND operator.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int findKOr(vector<int>& nums, int k) {
vector<int> freq(32);
for(auto n : nums) {
for(int i = 0; i < 32; i++) {
if(n & (1ll<<i)) freq[i] += 1;
}
}
int res = 0;
for(int i = 0; i < 32; i++) {
if(freq[i] < k) continue;
res |= 1ll<<i;
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/10/29/PS/LeetCode/find-the-k-or-of-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.