- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Calculating 1s in binary representation of numbers in JavaScript

## Problem

We are required to write a JavaScript function that takes in a single Integer, num, as the first and the only argument. Our function should prepare an array for every number between 0 and num (including both of them), for each number, the corresponding element should be the number of 1s contained in the binary representation of that number.

For example, if the input to the function is −

const num = 4;

Then the output should be −

const output = [0, 1, 1, 2, 1];

## Output Explanation:

Because 0 contains 0 1s in its binary form 1 contains 1, and so on.

## Example

The code for this will be −

const num = 4; const mapBinary = (num = 0) => { if (num === 0){ return [0]; }; const res = [0]; for (let i = 1; i <= num; i++) { const n = i % 2 === 0 ? res[i/2] : res[Math.floor(i/2)] + 1; res.push(n); }; return res; };

## Code Explanation:

While calculating the bits, there are some things we can keep in mind to make things easier for us.

numberOfBits(n) === numberOfBits(2*n) , Second result gets one more 0 bit compared to the first result.

if n is an even number, the last bit of n will be 0.

if n is an odd number, calculating the result could be considered as replacing the last bit of (n-1)/2 with 1, so we get equation numberOfBits(n) === numberOfBits(Math.floor(n / 2)) + 1 .

## Output

And the output in the console will be −

[ 0, 1, 1, 2, 1 ]