34 · Bit Manipulation

#338 Counting Bits

Easysolve on LeetCode ↗

frequently reported atMicrosoftGoogleAmazon

the problem

In plain words

Return an array ans of length n + 1 where ans[i] is the number of 1-bits in i, for every i from 0 to n. Can you do it in O(n) without a built-in popcount?

in n = 2

out [0,1,1]

in n = 5

out [0,1,1,2,1,2]

  • 0 ≤ n ≤ 10⁵

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #191
      Number of 1 Bits
      Easyin Bits
    2. #70
      Climbing Stairs
      Easyin Dynamic Programming
    3. #779
      K-th Symbol in Grammar
      Mediumin Recursion