2917. Find the K-th OR Value in an Array#
Given an integer array nums
and an integer k
, return the k-th
OR value of nums
.
The k-th
OR value of nums
is a non-negative integer that satisfies the following conditions:
- Only if there are at least
k
elements innums
whosei-th
bit is1
, then thei-th
bit of the OR value is1
.
Return the k-th
OR value of nums
.
Note: For an integer x
, if (2^i AND x) == 2^i
, then the i-th
bit of x
is 1
, where AND
is the bitwise AND operator.
Example 1:
Input: nums = [7,12,9,8,9,15], k = 4
Output: 9
Explanation: The `0-th` bit of nums[0], nums[2], nums[4], and nums[5] is `1`.
The `1-th` bit of nums[0] and nums[5] is `1`.
The `2-th` bit of nums[0], nums[1], and nums[5] is `1`.
The `3-th` bit of nums[1], nums[2], nums[3], nums[4], and nums[5] is `1`.
Only the `0-th` and `3-th` bits satisfy the condition that at least `k` elements in the array have a value of `1` in the corresponding bit.
Therefore, the answer is 2^0 + 2^3 = 9.
Example 2:
Input: nums = [2,12,1,11,4,5], k = 6
Output: 0
Explanation: Since k == 6 == nums.length, the `6-th` OR value of the array is the result of bitwise AND operation on all elements. Therefore, the answer is 2 AND 12 AND 1 AND 11 AND 4 AND 5 = 0.
Example 3:
Input: nums = [10,8,5,9,11,6,8], k = 1
Output: 15
Explanation: Since k == 1, the `1-th` OR value of the array is the result of bitwise OR operation on all elements. Therefore, the answer is 10 OR 8 OR 5 OR 9 OR 11 OR 6 OR 8 = 15.
Constraints:
1 <= nums.length <= 50
0 <= nums[i] < 2^31
1 <= k <= nums.length
Bit Manipulation#
class Solution {
public:
int findKOr(vector<int>& nums, int k) {
int res = 0;
for (int i = 0; i < 32; ++i) {
int cnt = 0;
for (const auto &num : nums) {
if ((num >> i) & 1) {
++cnt;
}
}
if (cnt >= k) {
res += (1 << i);
}
}
return res;
}
};