
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- Returning only odd number from array in JavaScript
- Binary array to corresponding decimal in JavaScript
- Returning the first number that equals its index in an array using JavaScript
- Returning array values that are not odd in JavaScript
- Remove item from a nested array by indices in JavaScript
- Longest distance between 1s in binary JavaScript
- Write a Golang program to convert a binary number to its decimal form
- Write a Golang program to convert a decimal number to its binary form
- Reversing the bits of a decimal number and returning new decimal number in JavaScript
- Returning the expanded form of a number in JavaScript
- Count numbers have all 1s together in binary representation in C++
- Evaluate a polynomial specified by its roots at points x in Python
- Calculating 1s in binary representation of numbers in JavaScript
- Sum array of rational numbers and returning the result in simplest form in JavaScript
- Returning just greater array in JavaScript

Advertisements