Returning a decimal that have 1s in its binary form only at indices specified by array in JavaScript


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 −

 Live Demo

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

Updated on: 20-Apr-2021

61 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements