Python 程式可計算一個整數中設定的位
本文中,我們將學習以下問題陳述的解決方案。
問題陳述 − 給定一個整數 n,我們需要計算該數的二進位制表示中 1 的個數
現在讓我們在下面的實現中觀察該解決方案 −
#簡單方法
示例
# count the bits
def count(n):
count = 0
while (n):
count += n & 1
n >>= 1
return count
# main
n = 15
print("The number of bits :",count(n))輸出
The number of bits : 4
#遞迴方法
示例
# recursive way
def count( n):
# base case
if (n == 0):
return 0
else:
# whether last bit is set or not
return (n & 1) + count(n >> 1)
# main
n = 15
print("The number of bits :",count(n))輸出
The number of bits : 4
結論
本文中,我們學習了編寫一個 Python 程式來計算一個整數中設定的位的方法。
廣告
資料結構
組網
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
JavaScript
PHP