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? By Ankit Rai Last updated : January 04, 2024

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)

Python program to find the number of required bits to represent a number

# 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

The output of the above example is:

4
6

To understand the above program, you should have the basic knowledge of the following Python topics:

Python Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.