[LeetCode] Construct the Minimum Bitwise Array II

3315. Construct the Minimum Bitwise Array II

You are given an array nums consisting of n prime integers.

You need to construct an array ans of length n, such that, for each index i, the bitwise OR of ans[i] and ans[i] + 1 is equal to nums[i], i.e. ans[i] OR (ans[i] + 1) == nums[i].

Additionally, you must minimize each value of ans[i] in the resulting array.

If it is not possible to find such a value for ans[i] that satisfies the condition, then set ans[i] = -1.

A prime number is a natural number greater than 1 with only two factors, 1 and itself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
bool bit(int x, int k) {
return (x>>k) & 1;
}
int helper(int x) {
if(x % 2 == 0) return -1;
int mask = INT_MAX;
for(int i = 0; i < 32; i++) {
if(bit(x,i)) continue;
return x ^ (1ll<<(i-1));
}
return -1;
}
public:
vector<int> minBitwiseArray(vector<int>& nums) {
vector<int> res;
for(auto& n : nums) res.push_back(helper(n));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/10/13/PS/LeetCode/construct-the-minimum-bitwise-array-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.