Isaac Emmanuel
15 Jun 2024•EasyC++ / Python / TypeScript

Counting Bits

C++, Python and TypeScript solutions for Counting Bits.

The Counting Bits solutions are below.

Solution files

Python•counting-bits/synced-solution.py
def countBits(n: int) -> list[int]:
    result = [0] * (n + 1)
    for i in range(1, n + 1):
        result[i] = result[i >> 1] + (i & 1)
    return result
C++•counting-bits/synced-solution.cpp
class Solution {
public:
    vector<int> countBits(int n) {
        vector<int> result(n + 1, 0);
        for (int i = 1; i <= n; i++) {
            result[i] = result[i >> 1] + (i & 1);
        }
        return result;
    }
};
TypeScript•counting-bits/synced-solution.ts
function countBits(n: number): number[] {
    const result = new Array(n + 1).fill(0);
    for (let i = 1; i <= n; i++) {
        result[i] = result[i >> 1] + (i & 1);
    }
    return result;
}