Problem
We are required to write a JavaScript function that takes in an array of unique non-negative integers. Our function should return a 32-bit integer such that the integer, in its binary representation, has 1 at only those indexes (counted from right) which are in the sequence.
Example
Following is the code −
const arr = [1, 2, 0, 4]; const buildDecimal = (arr = []) => { const bitArr = Array(31).fill(0); let res = 0; arr.forEach(el => { bitArr.splice((31 - el), 1, 1); }) bitArr.forEach((bit, index) => { res += (2 * (31-index) * bit); }); return res; }; console.log(buildDecimal(arr));
Output
Following is the console output −
14