Created
January 20, 2026 19:43
-
-
Save tatsuyax25/fa230c5687bc56e8703141b17641155e 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @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, and we can quickly verify | |
| // there is no x such that x | (x + 1) = 2. | |
| if (p === 2) { | |
| ans[i] = -1; | |
| continue; | |
| } | |
| // For odd primes, we will find the minimal x. | |
| // Strategy: | |
| // - Look at the binary representation of p. | |
| // - Find the highest bit position j such that: | |
| // * bit j of p is 1 | |
| // * all bits below j (0..j-1) are also 1 | |
| // - Then x = p - (1 << j) is a candidate. | |
| // - Using the highest such j gives the smallest x. | |
| let bestJ = -1; // best bit position found | |
| let allLowerOnes = true; // whether all bits below current j are 1 | |
| // We’ll scan bits from LSB (bit 0) upwards. | |
| let temp = p; | |
| let bitIndex = 0; | |
| while (temp > 0) { | |
| const bit = temp & 1; // current least significant bit | |
| if (bit === 0) { | |
| // If we see a 0 at this position, then for any higher bit j, | |
| // "all bits below j are 1" will be false once we pass here. | |
| allLowerOnes = false; | |
| } else { | |
| // bit == 1 | |
| // If all lower bits so far are 1, then this position j is valid. | |
| if (allLowerOnes) { | |
| bestJ = bitIndex; | |
| } | |
| } | |
| temp >>= 1; | |
| bitIndex++; | |
| } | |
| // For any odd prime p > 2, bestJ will be at least 0. | |
| // But we guard just in case. | |
| if (bestJ === -1) { | |
| ans[i] = -1; | |
| } else { | |
| ans[i] = p - (1 << bestJ); | |
| } | |
| } | |
| return ans; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment