×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

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? 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 »

Advertisement
Advertisement

Related Programs

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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