Python 中 1 位二進位制數的個數
假如我們有一個無符號數 n。我們需要在這個數的二進位制表示中找出 1 的個數。這也被稱為漢明重量。所以如果這個數是 000000101101,那麼結果將是 4。
為了解決這個問題,我們將使用以下步驟:
- 獲取這個數並將其轉換為一個二進位制字串
- 設定 count = 0
- 對於二進位制字串中的每個字元 e
- 如果該字元是‘1’,則將 count 增加 1
- 返回 count
示例
讓我們看看以下實現以獲得更好的理解:
class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ n = str(bin(n)) print(n) one_count = 0 for i in n: if i == "1": one_count+=1 return one_count num = "000000101101" ob1 = Solution() print(ob1.hammingWeight(num))
輸入
num = "000000101101"
輸出
4
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP