You are given an integer array nums, and an integer k. Let’s introduce
K-or operation by extending the standard bitwise OR. In K-or, a bit position in the result is set to 1 if at least k numbers in nums have a
1 in that position.
Input: nums =[7,12,9,8,9,15], k =4Output: 9Explanation:
Represent numbers in binary:**Number**| Bit 3| Bit 2| Bit 1| Bit 0---|---|---|---|---**7**|0|1|1|1**12**|1|1|0|0**9**|1|0|0|1**8**|1|0|0|0**9**|1|0|0|1**15**|1|1|1|1**Result =9**|1|0|0|1Bit 0is set in7,9,9, and 15. Bit 3is set in12,9,8,9, and 15.Only bits 0 and 3 qualify. The result is`(1001)2 = 9`.
Input: nums =[2,12,1,11,4,5], k =6Output: 0**Explanation:**No bit appears as 1in all six array numbers, as required
for K-or with`k = 6`. Thus, the result is0.
Input: nums =[10,8,5,9,11,6,8], k =1Output: 15Explanation: Since `k == 1`, the 1-or of the array is equal to the bitwise
OR of all its elements. Hence, the answer is`10 OR 8 OR 5 OR 9 OR 11 OR 6 OR
8 = 15`.
For each bit position, count how many numbers in the array have that bit set. If at least k numbers have a 1 at that position, set that bit in the result. This is a direct application of bit manipulation and counting.
classSolution {
public:int findKOr(vector<int>& nums, int k) {
int ans =0;
for (int b =0; b <32; ++b) {
int cnt =0;
for (int x : nums) {
if (x & (1<< b)) ++cnt;
}
if (cnt >= k) ans |= (1<< b);
}
return ans;
}
};
classSolution {
publicintfindKOr(int[] nums, int k) {
int ans = 0;
for (int b = 0; b < 32; ++b) {
int cnt = 0;
for (int x : nums) {
if ((x & (1 << b)) != 0) ++cnt;
}
if (cnt >= k) ans |= (1 << b);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funfindKOr(nums: IntArray, k: Int): Int {
var ans = 0for (b in0 until 32) {
var cnt = 0for (x in nums) {
if ((x shr b) and 1==1) cnt++ }
if (cnt >= k) ans = ans or (1 shl b)
}
return ans
}
}
1
2
3
4
5
6
7
8
classSolution:
deffindKOr(self, nums: list[int], k: int) -> int:
ans =0for b in range(32):
cnt = sum((x >> b) &1for x in nums)
if cnt >= k:
ans |= (1<< b)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnfind_k_or(nums: Vec<i32>, k: i32) -> i32 {
letmut ans =0;
for b in0..32 {
let cnt = nums.iter().filter(|&&x| (x >> b) &1==1).count();
if cnt asi32>= k {
ans |=1<< b;
}
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
findKOr(nums: number[], k: number):number {
letans=0;
for (letb=0; b<32; ++b) {
letcnt=0;
for (constxofnums) {
if ((x& (1<<b)) !==0) cnt++;
}
if (cnt>=k) ans|= (1<<b);
}
returnans;
}
}