Construct the Minimum Bitwise Array I

easy array bit manipulation bitwise OR

Problem

You are given an array nums of n prime integers. Build an array ans of length n so that for every index i the bitwise OR of ans[i] and ans[i] + 1 equals nums[i], that is ans[i] | (ans[i] + 1) == nums[i].

Among all valid choices, each ans[i] must be the minimum possible. If no value works, set ans[i] = -1.

Inputnums = [2, 3, 5, 7]
Output[-1, 1, 4, 3]
2 has no solution. 1 | 2 = 3, 4 | 5 = 5, and 3 | 4 = 7, each being the smallest that works.

def minBitwiseArray(nums):
    ans = []
    for num in nums:                     # solve each prime independently
        found = -1                       # default: no x satisfies the rule
        for x in range(num):             # x | (x+1) >= num, so x must be < num
            if (x | (x + 1)) == num:     # smallest x found first
                found = x
                break
        ans.append(found)
    return ans
function minBitwiseArray(nums) {
  const ans = [];
  for (const num of nums) {              // solve each prime independently
    let found = -1;                      // default: no x satisfies the rule
    for (let x = 0; x < num; x++) {      // x | (x+1) >= num, so x must be < num
      if ((x | (x + 1)) === num) {       // smallest x found first
        found = x;
        break;
      }
    }
    ans.push(found);
  }
  return ans;
}
int[] minBitwiseArray(int[] nums) {
    int[] ans = new int[nums.length];
    for (int i = 0; i < nums.length; i++) {  // solve each prime independently
        int num = nums[i], found = -1;       // default: no x satisfies the rule
        for (int x = 0; x < num; x++) {      // x | (x+1) >= num, so x must be < num
            if ((x | (x + 1)) == num) {      // smallest x found first
                found = x;
                break;
            }
        }
        ans[i] = found;
    }
    return ans;
}
vector<int> minBitwiseArray(vector<int>& nums) {
    vector<int> ans;
    for (int num : nums) {                   // solve each prime independently
        int found = -1;                      // default: no x satisfies the rule
        for (int x = 0; x < num; x++) {      // x | (x+1) >= num, so x must be < num
            if ((x | (x + 1)) == num) {      // smallest x found first
                found = x;
                break;
            }
        }
        ans.push_back(found);
    }
    return ans;
}
Time: O(n · max(nums)) Space: O(n)