/**
* Problem: LeetCode 3315 - Construct the Minimum Bitwise Array II
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
import java.util.List;
class Solution {
public int[] minBitwiseArray(List<Integer> nums) {
int n = nums.size();
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
int p = nums.get(i);
// Even prime (2) cannot be formed by x | (x + 1) because x | (x + 1) is always odd
if (p == 2) {
ans[i] = -1;
} else {
// (p + 1) & -(p + 1) isolates the lowest set bit of (p + 1), which equals 2^k
// where k is the number of trailing ones in p.
// Shifting right by 1 gives the highest set bit in the trailing ones block of p.
ans[i] = p - (((p + 1) & -(p + 1)) >> 1);
}
}
return ans;
}
}
"""
Problem: LeetCode 3315 - Construct the Minimum Bitwise Array II
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def minBitwiseArray(self, nums: List[int]) -> List[int]:
ans = []
for p in nums:
# Even prime (2) cannot be formed by x | (x + 1) because x | (x + 1) is always odd
if p == 2:
ans.append(-1)
else:
# Isolate the lowest set bit of p + 1 and divide by 2 to get
# the highest set bit in the contiguous trailing 1s of p.
lowbit = (p + 1) & -(p + 1)
ans.append(p - (lowbit >> 1))
return ans
/**
* Problem: LeetCode 3315 - Construct the Minimum Bitwise Array II
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
using namespace std;
class Solution {
public:
vector<int> minBitwiseArray(vector<int>& nums) {
int n = nums.size();
vector<int> ans(n);
for (int i = 0; i < n; i++) {
int p = nums[i];
// Even prime (2) cannot be formed by x | (x + 1) because x | (x + 1) is always odd
if (p == 2) {
ans[i] = -1;
} else {
// Find lowest set bit of (p + 1) and shift right by 1
ans[i] = p - (((p + 1) & -(p + 1)) >> 1);
}
}
return ans;
}
};
/**
* Problem: LeetCode 3315 - Construct the Minimum Bitwise Array II
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {number[]} nums
* @return {number[]}
*/
var minBitwiseArray = function(nums) {
const n = nums.length;
const ans = new Array(n);
for (let i = 0; i < n; i++) {
const p = nums[i];
// Even prime (2) cannot be formed by x | (x + 1) because x | (x + 1) is always odd
if (p === 2) {
ans[i] = -1;
} else {
// Find lowest set bit of (p + 1), then right shift by 1 to get highest bit in trailing 1s of p
ans[i] = p - (((p + 1) & -(p + 1)) >> 1);
}
}
return ans;
};