[LeetCode] Construct the Minimum Bitwise Array I

3314. Construct the Minimum Bitwise Array I

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
class Solution {
int helper(int x) {
for(int i = 1; i <= x; i++) {
if((i | (i + 1)) == x) return i;
}
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-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.