150強訪談簡單

1 位數

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

問題陳述

簡單

編寫一個函數,採用正整數的二進位表示形式並傳回其所設定的位數(也稱為漢明權重)。

寫一個函數 hammingWeight(n: int) -> int

約束條件
  • n must be a positive integer up to 2^32 - 1

範例

Example 1
Input
n = 11
Output
3
Explanation

The binary representation of 11 is 1011, which has 3 set bits.

Example 2
Input
n = 128
Output
1
Explanation

The binary representation of 128 is 10000000, which has 1 set bit.

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

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