Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Bin | Count total bits in a number
Next article icon

Python Bin | Count total bits in a number

Last Updated : 05 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a positive number n, count total bit in it.
 

Examples: 
 

Input : 13 Output : 4 Binary representation of 13 is 1101  Input  : 183 Output : 8  Input  : 4096 Output : 13


 


We have existing solution for this problem please refer Count total bits in a number link.

Approach#1:  We can solve this problem quickly in Python using bin() function. Convert number into it's binary using bin() function and remove starting two characters '0b' of output binary string because bin function appends '0b' as prefix in output string. Now print length of binary string that will be the count of bits in binary representation of input number.
 

Python3
# Function to count total bits in a number  def countTotalBits(num):           # convert number into it's binary and       # remove first two characters .      binary = bin(num)[2:]      print(len(binary))   # Driver program if __name__ == "__main__":     num = 13     countTotalBits(num) 

Output
4

Approach#2: We can solve this problem by simply using bit_length function of integer. This function returns the number of bits required to represent the number in binary form. 

Python3
# Function to count total bits in a number  def countTotalBits(num):           # bit_length function return       # total bits in number       B_len = num.bit_length()      print("Total bits in binary are : ", B_len)   # Driver program if __name__ == "__main__":     num = 13     countTotalBits(num) 

Output
Total bits in binary are :  4

Approach#3: Using math

approach to count the total number of bits in a number is to use the logarithmic function log2() from the math module. Since the logarithmic function base 2 tells us the number of bits required to represent a number in binary, we can use it to calculate the total number of bits in a number.

Algorithm

1. Import the math module.
2. Define a function count_bits that takes an integer num as input.
3. Calculate the logarithm base 2 of the input number using the log2() function from the math module.
4. Add 1 to the result of the logarithm calculation to account for the sign bit (if the number is negative).
5. Return the integer value of the result.

Python3
import math  def count_bits(num):     return int(math.log2(num)) + 1  num=13 print(count_bits(num)) 

Output
4

Time complexity:
The time complexity of this function is O(1) because the log2() function and the addition operation both have constant time complexity.

Auxiliary Space:
The space complexity of this function is O(1) because the only extra space used is for storing the integer value of the result, which has a constant size regardless of the input size.

METHOD 4:Using defaultdict

APPRAOCH:

 This program counts the total number of bits in a given number using a defaultdict data structure.

ALGORITHM:

1.Convert the given number to its binary representation using the built-in bin() function.
2.Create a defaultdict to count the number of '0's and '1's in the binary representation.
3.Iterate over the binary representation and increment the corresponding count in the defaultdict.
4.Add the counts of '0's and '1's to get the total number of bits in the binary representation.

Python3
from collections import defaultdict  # Function to count the number of bits def count_bits(num):     binary = bin(num)[2:]     bit_count = defaultdict(int)     for bit in binary:         bit_count[bit] += 1     return bit_count['1'] + bit_count['0']   # Driver Code num = 13 bits = count_bits(num)  print("Total bits in", num, ":", bits) 

Output
Total bits in 13 : 4

Time Complexity: O(log n), where n is the given number.

Space Complexity: O(log n), where n is the given number, due to the storage of the binary representation in memory and the creation of the defaultdict.


Next Article
Python Bin | Count total bits in a number

S

Shashank Mishra
Improve
Article Tags :
  • Python
  • DSA
Practice Tags :
  • python

Similar Reads

    Count total bits in a number
    Given a positive number n, count total bit in it.Examples: Input : 13 Output : 4 Binary representation of 13 is 1101 Input : 183 Output : 8 Input : 4096 Output : 13 Method 1 (Using Log) The log2(n) logarithm in base 2 of n, which is the exponent to which 2 is raised to get n only integer and we add
    7 min read
    numpy.bincount() in Python
    In an array of +ve integers, the numpy.bincount() method counts the occurrence of each element. Each bin value is the occurrence of its index. One can also set the bin size accordingly. Syntax : numpy.bincount(arr, weights = None, min_len = 0) Parameters : arr : [array_like, 1D]Input array, having p
    2 min read
    Count total unset bits in all the numbers from 1 to N
    Given a positive integer N, the task is to count the total number of unset bits in the binary representation of all the numbers from 1 to N. Note that leading zeroes will not be counted as unset bits.Examples: Input: N = 5 Output: 4 IntegerBinary RepresentationCount of unset bits11021013110410025101
    4 min read
    Convert Bytes To Bits in Python
    Converting bytes to bits in Python involves representing each byte in its binary form, where each byte is composed of 8 bits. For example , a byte like 0xAB (which is 171 in decimal) would be represented as '10101011' in binary. Let’s explore a few techniques to convert bytes to bits in Python.Using
    2 min read
    Count unset bits of a number
    Given a number n, count unset bits after MSB (Most Significant Bit).Examples : Input : 17 Output : 3 Binary of 17 is 10001 so unset bit is 3 Input : 7 Output : 0 A Simple Solution is to traverse through all bits and count unset bits. C++ // C++ program to count unset bits in an integer #include <
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences