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
-
Economics & Finance
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 ?
23
How It Works
The function creates a 31-element array filled with zeros, then sets bits to 1 at positions specified in the input array. For array [1, 2, 0, 4], it creates a binary number with 1s at positions 0, 1, 2, and 4 (from right), resulting in binary 10111, which equals 23 in decimal.
Optimized Solution Using Bitwise Operations
A more efficient approach uses bitwise left shift operations:
const buildDecimalOptimized = (arr = []) => {
let result = 0;
arr.forEach(index => {
result |= (1
23
10111
Comparison
| Method | Time Complexity | Space Complexity | Efficiency |
|---|---|---|---|
| Array-based | O(n + 31) | O(31) | Less efficient |
| Bitwise operations | O(n) | O(1) | More efficient |
Conclusion
The bitwise approach using left shift and OR operations is more efficient for converting array indices to decimal. It directly manipulates bits without creating intermediate arrays, making it both faster and more memory-efficient.
