Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Count number of set bits in a range using bitset
Next article icon

Count set bits in an integer using Lookup Table

Last Updated : 03 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Write an efficient program to count number of 1s in binary representation of an integer.
Examples: 

Input : n = 6
Output : 2
Binary representation of 6 is 110 and has 2 set bits

Input : n = 13
Output : 3
Binary representation of 13 is 1101 and has 3 set bits


 


In the previous post we had seen different method that solved this problem in O(log n) time. In this post we solve in O(1) using lookup table. Here we assume that the size of INT is 32-bits. It’s hard to count all 32 bits in one go using lookup table (” because it’s infeasible to create lookup table of size 232-1 “). So we break 32 bits into 8 bits of chunks( How lookup table of size (28-1 ) index : 0-255 ).
LookUp Table 
In lookup tale, we store count of set_bit of every 
number that are in a range (0-255) 
LookupTable[0] = 0 | binary 00000000 CountSetBits 0 
LookupTable[1] = 1 | binary 00000001 CountSetBits 1 
LookupTable[2] = 1 | binary 00000010 CountSetBits 1 
LookupTable[3] = 2 | binary 00000011 CountSetBits 2 
LookupTable[4] = 1 | binary 00000100 CountSetBits 1 
and so…on upto LookupTable[255].
Let’s take an Example How lookup table work.
 

Let's number be : 354 
in Binary : 0000000000000000000000101100010

Split it into 8 bits chunks :
In Binary : 00000000 | 00000000 | 00000001 | 01100010
In decimal : 0 0 1 98

Now Count Set_bits using LookupTable
LookupTable[0] = 0
LookupTable[1] = 1
LookupTable[98] = 3

so Total bits count : 4


 Below is the code implementation of the above approach:

CPP
// C++ Program to count number of set bits // using lookup table in O(1) time  #include <iostream> using namespace std;  // Generate a lookup table for 32 bit integers #define B2(n) n, n + 1, n + 1, n + 2 #define B4(n) B2(n), B2(n + 1), B2(n + 1), B2(n + 2) #define B6(n) B4(n), B4(n + 1), B4(n + 1), B4(n + 2)  // Lookup table that store the reverse of each table unsigned int lookuptable[256]     = { B6(0), B6(1), B6(1), B6(2) };  // function countset Bits Using lookup table // ans return set bits count unsigned int countSetBits(int N) {     // first chunk of 8 bits from right     unsigned int count = lookuptable[N & 0xff] +                           // second chunk from  right                          lookuptable[(N >> 8) & 0xff] +                           // third and fourth chunks                          lookuptable[(N >> 16) & 0xff]                          + lookuptable[(N >> 24) & 0xff];     return count; }  int main() {     unsigned int N = 354;     cout << countSetBits(N) << endl;      return 0; } 
Java
// Java count to count number of set bits // using lookup table in O(1) time  // Generate a lookup table for 32 bit integers import java.util.*;  class GFG {     static ArrayList<Integer> lookuptable         = new ArrayList<Integer>();      static void B2(int n)     {         lookuptable.add(n);         lookuptable.add(n + 1);         lookuptable.add(n + 1);         lookuptable.add(n + 2);     }      static void B4(int n)     {         B2(n);         B2(n + 1);         B2(n + 1);         B2(n + 2);     }      static void B6(int n)     {         B4(n);         B4(n + 1);         B4(n + 1);         B4(n + 2);     }      // function countset Bits Using lookup table     // ans return set bits count     static int countSetBits(int N)     {         // adding the bits in chunks of 8 bits         int count = lookuptable.get(N & 0xff)                     + lookuptable.get((N >> 8) & 0xff)                     + lookuptable.get((N >> 16) & 0xff)                     + lookuptable.get((N >> 24) & 0xff);         return count;     }      // Driver Code     public static void main(String[] args)     {         // Lookup table that store the reverse of each table         B6(0);         B6(1);         B6(1);         B6(2);          int N = 354;          // Function Call         System.out.println(countSetBits(N));     } }  // This code is contributed by phasing17 
Python
# Python3 count to count number of set bits # using lookup table in O(1) time  # Generate a lookup table for 32 bit integers  lookuptable = []   def B2(n):     lookuptable.extend([n, n + 1, n + 1, n + 2])   def B4(n):     B2(n), B2(n + 1), B2(n + 1), B2(n + 2)   def B6(n):     B4(n), B4(n + 1), B4(n + 1), B4(n + 2)   # Lookup table that store the reverse of each table lookuptable.extend([B6(0), B6(1), B6(1), B6(2)])  # function countset Bits Using lookup table # ans return set bits count   def countSetBits(N):      # adding the bits in chunks of 8 bits     count = lookuptable[N & 0xff] + lookuptable[(N >> 8) & 0xff] + lookuptable[(         N >> 16) & 0xff] + lookuptable[(N >> 24) & 0xff]     return count   # Driver Code N = 354  # Function Call print(countSetBits(N))   # This code is contributed by phasing17 
C#
// C# count to count number of set bits // using lookup table in O(1) time  // Generate a lookup table for 32 bit integers  using System; using System.Collections.Generic;  class GFG {     static List<int> lookuptable = new List<int>();      static void B2(int n)     {         lookuptable.Add(n);         lookuptable.Add(n + 1);         lookuptable.Add(n + 1);         lookuptable.Add(n + 2);     }      static void B4(int n)     {         B2(n);         B2(n + 1);         B2(n + 1);         B2(n + 2);     }      static void B6(int n)     {         B4(n);         B4(n + 1);         B4(n + 1);         B4(n + 2);     }      // function countset Bits Using lookup table     // ans return set bits count     static int countSetBits(int N)     {         // adding the bits in chunks of 8 bits         int count = lookuptable[N & 0xff]                     + lookuptable[(N >> 8) & 0xff]                     + lookuptable[(N >> 16) & 0xff]                     + lookuptable[(N >> 24) & 0xff];         return count;     }      // Driver Code     public static void Main(string[] args)     {         // Lookup table that store the reverse of each table         B6(0);         B6(1);         B6(1);         B6(2);          int N = 354;          // Function Call         Console.WriteLine(countSetBits(N));     } }  // This code is contributed by phasing17 
JavaScript
// JavaScript count to count number of set bits // using lookup table in O(1) time  // Generate a lookup table for 32 bit integers  let lookuptable = [];   function B2(n) {     lookuptable.push(n);     lookuptable.push(n + 1);     lookuptable.push(n + 1);     lookuptable.push(n + 2); }   function B4(n) {     B2(n), B2(n + 1), B2(n + 1), B2(n + 2) }   function B6(n) {     B4(n), B4(n + 1), B4(n + 1), B4(n + 2) }   // Lookup table that store the reverse of each table lookuptable.push(B6(0)); lookuptable.push(B6(1)); lookuptable.push(B6(1)); lookuptable.push(B6(2));   // function countset Bits Using lookup table // ans return set bits count function countSetBits(N) {     // adding the bits in chunks of 8 bits     let count = lookuptable[N & 0xff] + lookuptable[(N >> 8) & 0xff] + lookuptable[(N >> 16) & 0xff] + lookuptable[(N >> 24) & 0xff];     return count; }   // Driver Code let N = 354;  // Function Call console.log(countSetBits(N));   // This code is contributed by phasing17 

Output:  

4 

Time Complexity: O(1)
Auxiliary Space: O(1) 



Next Article
Count number of set bits in a range using bitset

N

Nishant_Singh
Improve
Article Tags :
  • Bit Magic
  • DSA
Practice Tags :
  • Bit Magic

Similar Reads

  • Count set bits in an integer
    Write an efficient program to count the number of 1s in the binary representation of an integer.Examples : Input : n = 6Output : 2Binary representation of 6 is 110 and has 2 set bits Input : n = 13Output : 3Binary representation of 13 is 1101 and has 3 set bits [Naive Approach] - One by One Counting
    15+ min read
  • Reverse bits using lookup table in O(1) time
    Given an unsigned integer, reverse all bits of it and return the number with reversed bits. Examples: Input : n = 1 Output : 2147483648 On a machine with size of unsigned bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648 Output : 1 In the previous post we had seen two method that so
    7 min read
  • Count unset bits in a range
    Given a non-negative number n and two values l and r. The problem is to count the number of unset bits in the range l to r in the binary representation of n, i.e, to count unset bits from the rightmost lth bit to the rightmost rth bit.Examples: Input : n = 42, l = 2, r = 5 Output : 2 (42)10 = (10101
    6 min read
  • Count number of set bits in a range using bitset
    Given a large binary number.The task is to count the number of 1's in a given range from L to R (1 based indexing).Examples: Input : s = "101101011010100000111", L = 6, R = 15 Output : 5 s [L : R] = "1011010100" There is only 5 set bits.Input : s = "10110", L = 2, R = 5 Output : 2 Approach: Convert
    5 min read
  • Count of N-bit odd and even integers with K set bits
    Given two positive integers N and K, the task is to count the number of even and odd integers consisting of N bits, out of which K bits are set. Examples: Input: N = 5, K = 2Output: 3 1Explanation:The 5 bit even integers having 2 set bits are: 10010(= 18), 10100(= 20), 11000(= 24). So, the count is
    6 min read
  • Count trailing zero bits using lookup table
    Given an integer, count the number of trailing zeroes. For example, for n = 12, its binary representation is 1100 and number of trailing zero bits is 2. Examples : Input : 8 Output : 3 Binary of 8 is 1000, so there are three trailing zero bits. Input : 18 Output : 1 Binary of 18 is 10010, so there i
    7 min read
  • 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
  • Count set bits in a range
    Given a non-negative number n and two values l and r. The problem is to count the number of set bits in the range l to r in the binary representation of n, i.e, to count set bits from the rightmost lth bit to the rightmost rth bit. Constraint: 1 <= l <= r <= number of bits in the binary rep
    6 min read
  • Python Bin | 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 We have existing solution for this problem please refer Count total bits in a number link. Approach#1: We can solve this problem quick
    3 min read
  • Count Set-bits of number using Recursion
    Given a positive integer n, the task is to find the number of set bits in its binary representation using recursion. Examples: Input : 21 Output : 3 Explanation: 21 represented as 10101 in binary representation. Input : 16 Output : 1 Explanation: 16 represented as 10000 in binary representation. Usi
    3 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