Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created January 21, 2026 18:23
Show Gist options
  • Select an option

  • Save tatsuyax25/f1cd7f07dba4f3cb06839ef86df42de5 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/f1cd7f07dba4f3cb06839ef86df42de5 to your computer and use it in GitHub Desktop.
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]. Additional
/**
* @param {number[]} nums
* @return {number[]}
*/
var minBitwiseArray = function(nums) {
const ans = new Array(nums.length);
for (let i = 0; i < nums.length; i++) {
const p = nums[i];
// The only even prime is 2.
// If p == 2, its binary is '10' (no trailing 1s),
// and there is no x such that x | (x + 1) == 2.
if (p === 2) {
ans[i] = -1;
continue;
}
// For any odd prime p > 2, the least significant bit is 1,
// so there is at least one trailing 1.
// We now count how many consecutive 1s appear from the LSB upward.
let k = 0;
let temp = p;
while ((temp & 1) === 1) {
k++;
temp >>= 1;
}
// k is the number of trailing 1s in p.
// Valid t are 0..k-1, and to minimize x = p - 2^t,
// we choose the largest t = k - 1.
const t = k - 1;
// Compute x = p - 2^t.
ans[i] = p - (1 << t);
}
return ans;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment