LeetCode-in-Java

3315. Construct the Minimum Bitwise Array II

Medium

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.

Example 1:

Input: nums = [2,3,5,7]

Output: [-1,1,4,3]

Explanation:

Example 2:

Input: nums = [11,13,31]

Output: [9,12,15]

Explanation:

Constraints:

Solution

import java.util.List;

public class Solution {
    public int[] minBitwiseArray(List<Integer> nums) {
        final int n = nums.size();
        int[] result = new int[n];
        for (int i = 0; i < n; i++) {
            int num = nums.get(i);
            result[i] = -1;
            int p = 0;
            for (; p < 31; p++) {
                if (((num >> p) & 1) == 0) {
                    break;
                }
            }
            if (p > 0) {
                result[i] = ((num >> p) << p) | ((1 << (p - 1)) - 1);
            }
        }
        return result;
    }
}