Created
August 11, 2025 15:42
-
-
Save tatsuyax25/cdb28cc782a6ec31eb26ae7bbedd8d9b to your computer and use it in GitHub Desktop.
Given a positive integer n, there exists a 0-indexed array called powers, composed of the minimum number of powers of 2 that sum to n. The array is sorted in non-decreasing order, and there is only one way to form the array. You are also given a 0-i
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} n | |
* @param {number[][]} queries | |
* @return {number[]} | |
*/ | |
var productQueries = function(n, queries) { | |
const MOD = 1e9 + 7; | |
// Step 1: Decompose n into powers of 2 using its binary representation | |
const powers = []; | |
for (let i = 0; i < 32; i++) { | |
// Check if the ith bit is set | |
if ((n & (1 << i)) !== 0) { | |
powers.push(1 << i); // Add 2^i to the powers array | |
} | |
} | |
// Step 2: Sort powers in non-decreasing order (though binary decomposition already gives that) | |
powers.sort((a, b) => a - b); | |
// Step 3: Process each query | |
const answers = []; | |
for (const [left, right] of queries) { | |
let product = 1; | |
for (let i = left; i <= right; i++) { | |
product = (product * powers[i]) % MOD; | |
} | |
answers.push(product); | |
} | |
return answers; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment