Home »
Python »
Python programs
Python program to find the number of required bits to represent a number in O(1) complexity
Here, we will learn how to find the number of required bits to represent anumber in O(1) complexity using python?
Submitted by Ankit Rai, on June 15, 2019
Problem statement
Find total Number of bits required to represent a number in binary
Example 1:
input : 10
output: 4
Example 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
Python Basic Programs »
ADVERTISEMENT
ADVERTISEMENT