Counting Bits easy
Problem Statement
Given an integer n
, return an array ans
of length n + 1
such that for each i
(0 <= i
<= n
), ans[i]
is the number of 1's in the binary representation of i
.
Example 1:
Input: n = 2 Output: [0,1,1] Explanation: 0 --> 0 1 --> 1 2 --> 10
Example 2:
Input: n = 5 Output: [0,1,1,2,1,2] Explanation: 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101
Steps:
-
Initialization: Create an array
ans
of sizen + 1
and initialize the first elementans[0]
to 0 (since the binary representation of 0 has zero 1s). -
Iteration: Iterate from
i = 1
ton
. For eachi
, count the number of 1s in its binary representation. We can do this efficiently using bit manipulation. -
Bit Counting: There are several ways to count 1s in a binary number. One efficient method is to repeatedly apply the bitwise AND operation (
&
) withi - 1
. This operation clears the least significant set bit. We can repeat this untili
becomes 0, incrementing a counter each time. Alternatively, we can use the built-inSystem.Numerics.BitOperations.PopCount()
method (available in .NET 5 and later). -
Storing Results: Store the count of 1s in
ans[i]
. -
Return: Return the
ans
array.
Explanation:
The key to efficiently solving this problem is understanding how to count the number of set bits (1s) in a binary number. The iterative approach using i & (i - 1)
is particularly efficient because it directly removes the rightmost set bit in each iteration. This avoids the need for explicit bit shifting or string conversions. The System.Numerics.BitOperations.PopCount()
method provides a highly optimized built-in solution for counting set bits.
Code:
using System;
using System.Numerics; // For BitOperations.PopCount()
public class Solution {
public int[] CountBits(int n) {
int[] ans = new int[n + 1];
ans[0] = 0;
for (int i = 1; i <= n; i++) {
//Efficient method using BitOperations.PopCount() (available from .NET 5 onwards)
ans[i] = BitOperations.PopCount(i);
//Alternative method (works for earlier .NET versions)
//int count = 0;
//int temp = i;
//while (temp > 0) {
// temp &= (temp - 1);
// count++;
//}
//ans[i] = count;
}
return ans;
}
}
Complexity:
-
Time Complexity: O(n log n) using the iterative approach (because the number of iterations in the inner loop is proportional to the number of bits, which is log n). O(n) using
BitOperations.PopCount()
assuming the built-in function has O(1) complexity. -
Space Complexity: O(n) to store the
ans
array.