150強訪談簡單

計數位

“計數位元”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個整數 n,傳回一個長度為 n + 1 的陣列 ans,這樣對於每個 i (0 <= i <= n),ans[i] 是 i 的二進位表示形式中 1 的數量。

寫一個函數 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?
考慮使用特定於位操作的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。