Skip to content

Instantly share code, notes, and snippets.

@Ephraimiyanda
Created February 8, 2026 10:35
Show Gist options
  • Select an option

  • Save Ephraimiyanda/3c7788311256bc77dbb06b02e7e49d33 to your computer and use it in GitHub Desktop.

Select an option

Save Ephraimiyanda/3c7788311256bc77dbb06b02e7e49d33 to your computer and use it in GitHub Desktop.
Counting Bits

Question

Approach

  1. Create a loop which runsfor n+1 times.
  2. Inside the loop i find the binary representation for the index value.
  3. I then move to find the amount of 1 in the binary representation and add it to the ans array

Complexity

  • Time complexity:O(NLogN)

  • Space complexity:O(N)

Code

function countBits(n: number): number[] {
    let ans:number[] = []
    for (let i = 0; i < n+1; i++) {
        let bin =i.toString(2)
        let ones = bin.split("").filter((num) => num === "1").length
        ans.push(Number(ones))
    }
    return  ans
};
scrnli_t8mK9DfuYlLM4T
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment