Problem statement
問題陳述
Find total Number of bits required to represent a number in binary
查找以二進制表示數字所需的總位數
Example 1:
范例1:
input : 10
output: 4
Example 2:
范例2:
input : 32
output : 6
Formula used:
使用的公式:
Bits_required = floor(log2(number) + 1)
Code:
碼:
# From math module import log2 and floor function
from math import log2,floor
# Define a function for finding number of bits
# required to represent any number
def countBits(Num) :
bits = floor(log2(Num) + 1)
return bits
if __name__ == "__main__" :
# assign number
Num = 10
# function call
print(countBits(Num))
Num = 32
print(countBits(Num))
Output
輸出量
4
6
翻譯自: https://www.includehelp.com/python/find-the-number-of-required-bits-to-represent-a-number-in-O-1-complexity.aspx