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
Calculating 1s in binary representation of numbers in JavaScript
We need to write a JavaScript function that takes an integer num and returns an array where each element represents the count of 1s in the binary representation of numbers from 0 to num.
Problem
Given a number num, create an array where:
Index
icontains the count of 1s in binary representation ofiArray includes elements for numbers 0 through
num(inclusive)
For example, if num = 4:
Input: 4 Output: [0, 1, 1, 2, 1]
Output Explanation
Let's break down the binary representations:
| Number | Binary | Count of 1s |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 1 | 1 |
| 2 | 10 | 1 |
| 3 | 11 | 2 |
| 4 | 100 | 1 |
Method 1: Using Built-in Methods
The simplest approach uses JavaScript's built-in methods to convert numbers to binary and count 1s:
const countBits = (num) => {
const result = [];
for (let i = 0; i <= num; i++) {
const binaryString = i.toString(2);
const onesCount = binaryString.split('1').length - 1;
result.push(onesCount);
}
return result;
};
console.log(countBits(4));
console.log(countBits(6));
[ 0, 1, 1, 2, 1 ] [ 0, 1, 1, 2, 1, 2, 2 ]
Method 2: Dynamic Programming (Optimized)
A more efficient approach uses the relationship between numbers and their binary representations:
const mapBinary = (num = 0) => {
if (num === 0) {
return [0];
}
const res = [0];
for (let i = 1; i <= num; i++) {
// If even: same as i/2, if odd: same as floor(i/2) + 1
const n = i % 2 === 0 ? res[i/2] : res[Math.floor(i/2)] + 1;
res.push(n);
}
return res;
};
console.log(mapBinary(4));
console.log(mapBinary(8));
[ 0, 1, 1, 2, 1 ] [ 0, 1, 1, 2, 1, 2, 2, 3, 1 ]
How the Optimization Works
The dynamic programming approach leverages these patterns:
Even numbers: The count equals the count for
n/2(shifting right removes a 0)Odd numbers: The count equals the count for
floor(n/2)plus 1 (shifting right removes a 1)
Method 3: Bit Manipulation
Using bitwise operations for direct bit counting:
const countBitsBitwise = (num) => {
const result = [];
for (let i = 0; i <= num; i++) {
let count = 0;
let n = i;
while (n > 0) {
count += n & 1; // Add 1 if last bit is 1
n >>= 1; // Right shift by 1
}
result.push(count);
}
return result;
};
console.log(countBitsBitwise(5));
[ 0, 1, 1, 2, 1, 2 ]
Performance Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Built-in Methods | O(n log n) | O(1) | High |
| Dynamic Programming | O(n) | O(1) | Medium |
| Bit Manipulation | O(n log n) | O(1) | Low |
Conclusion
The dynamic programming approach offers the best time complexity O(n) by reusing previously computed results. For small datasets, the built-in method provides better readability with acceptable performance.
