Computer >> Máy Tính >  >> Lập trình >> Python

Viết chương trình python để đếm tổng số bit trong một số?

Đầu tiên, chúng tôi nhập một số, sau đó chuyển đổi số này thành số nhị phân bằng cách sử dụng hàm bin () và tiếp theo xóa hai ký tự đầu tiên ‘0b’ của chuỗi đầu ra, tiếp theo tính độ dài của chuỗi nhị phân.

Ví dụ

Input:200
Output:8

Giải thích

Binary representation of 200 is 10010000

Thuật toán

Step 1: input number.
Step 2: convert number into its binary using bin() function.
Step 3: remove first two characters ‘0b’ of output binary string because bin function appends ‘ob’ a prefix in output string.
Step 4: then calculate the length of the binary string.

Mã mẫu

# Python program to count total bits in a number
def totalbits(n):
   binumber = bin(n)[2:]
   print("TOTAL BITS ::>",len(binumber)) 
# Driver program
if __name__ == "__main__":
   n=int(input("Enter Number ::>"))
   totalbits(n)

Đầu ra

Enter Number ::>200
TOTAL BITS ::> 8