Q:

Python program to find the number of required bits to represent a number in O(1) complexity

belongs to collection: Python basic programs

0

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)

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python basic programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to count number of trailing zeros i... >>
<< Python program to convert temperature from Celsius...