LeetCode 338: Counting Bits

Problem Overview
Given an integer n, return an array ans of length n + 1 where ans[i] is the number of set bits in the binary representation of i.
Example:
n = 5→ Output:[0, 1, 1, 2, 1, 2]Constraints:
0 <= n <= 10^5
Solution 1: Brute Force
This is the most intuitive approach. We iterate through each number from 0 to n, and for each number, we manually count its set bits.
The Algorithm for counting bits of a single number i:
Initialize a counter for the current number, e.g.,
count = 0.Use a temporary variable
temp_num = ito avoid modifying the main loop’s counter.Use a
whileloop that continues as long astemp_numis not 0.Check the LSB: Use the bitwise AND operator(&) to check if the least significant bit is a 1.
Shift to the Next Bit: Use the right shift operator (
>>) to discard the LSB.The loop terminates when the number becomes 0.
C++ implementation:
class Solution {
public:
vector<int> countBits(int n) {
vector<int> ans(n + 1);
for (int i = 0; i <= n; ++i) {
// Logic to count bits for each number 'i'
int count = 0;
int temp_num = i;
while (temp_num != 0) {
if ((temp_num & 1) == 1) { // or simply: if (temp_num & 1)
count++;
}
temp_num = temp_num >> 1;
}
ans[i] = count;
}
return ans;
}
};
Complexity Analysis:
Time Complexity: O(n * log(n))
The outer
forloop runs n + 1 times.The inner
whileloop runs for a number of times equal to the number of bits ini, which is approximately log(i).
Space Complexity: O(n)
- We need O(n) space for the
ansarray that we return.
- We need O(n) space for the


