Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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 −
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
Advertisements
