Counting Bits

Easy
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start•← → to step•? all shortcuts

Solution Guide: Counting Bits

Approach

Build a DP table where ans[i] reuses the already-computed count for i >> 1 (integer division by 2) and adds 1 if i is odd (i & 1). This avoids recomputing bit counts from scratch for each number.

Complexity Analysis

Time
O(n)
Space
O(n)

Pattern

Bit Counting DP

Why It Works

Right-shifting by 1 removes the least significant bit, and that bit count is already stored in the table. Adding back whether the removed bit was 1 completes the count.

Updated Mar 2026