- Related Questions & Answers
- Count numbers have all 1s together in binary representation in C++
- Sorting according to number of 1s in binary representation using JavaScript
- 1 to n bit numbers with no consecutive 1s in binary representation?
- XOR counts of 0s and 1s in binary representation in C++
- Find consecutive 1s of length >= n in binary representation of a number in C++
- Calculating the LCM of multiple numbers in JavaScript
- Longest distance between 1s in binary JavaScript
- Calculating variance for an array of numbers in JavaScript
- Array Representation Of Binary Heap
- Check if the binary representation of a number has equal number of 0s and 1s in blocks in Python
- Binary representation of next number in C++
- Binary representation of previous number in C++
- Python program to check if binary representation of two numbers are anagram.
- Converting numbers to base-7 representation in JavaScript
- Binary representation of a given number in C++

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

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];

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

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; };

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 .

And the output in the console will be −

[ 0, 1, 1, 2, 1 ]

Advertisements