Top 150 Interview簡単

Counting Bits

Detailed guide and Python implementation for the 'Counting Bits' problem.

問題提起

簡単

Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.

Write a function countBits(n: int) -> List[int].

制約
  • 0 <= n <= 10^5

Example 1
Input
n = 2
Output
[0,1,1]
Explanation

0 -> 0; 1 -> 1; 2 -> 10.

Example 2
Input
n = 5
Output
[0,1,1,2,1,2]
Explanation

0 -> 0; 1 -> 1; 2 -> 1; 3 -> 2; 4 -> 1; 5 -> 2.

Need a Hint?
Consider using Bit Manipulation-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

解決する準備はできましたか?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

エディタで開く
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推奨される Python リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。