Problem
The binary form of a number uses only the digits 0 and 1. Each digit is a bit.
You get an integer n. Return an array ans with n + 1 items. For each i from 0 to n, ans[i] is the number of bits with the value 1 in the binary form of i.
Example 1
- Input:
- n = 3
- Output:
- [0,1,1,2]
- Explanation:
- In binary, 0 is
0, 1 is1, 2 is10and 3 is11.
Example 2
- Input:
- n = 6
- Output:
- [0,1,1,2,1,2,2]
- Explanation:
- The binary forms of 4, 5 and 6 are
100,101and110.
Constraints
- 0 <= n <= 10^5
Follow-up
A simple solution runs in O(n log n) time. Can you find an O(n) solution that does not use a built-in function to count bits?
SysRound wrote this statement. A reference solution checks every example.
Related questions
Continue with questions that share topics or the same question type.
Sources · 1 reference
These records explain where the question appears. A company tag or candidate report does not guarantee a future interview question.
Hello Interview · 1 record
No company association
Leetcode 338. Counting Bits
Reported date not specified · 0 source reports
Source snapshot: Nov 12, 2026
View source