Write an efficient program to count number of 1s in binary representation of an integer.
Input : n = 6 Output : 2 Binary representation of 6 is 110 and has 2 set bits Input : n = 13 Output : 3 Binary representation of 11 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( ow lookup table of size (28-1 ) index : 0-255 ).
In lookup tale, we store count of set_bit of every
number that are in a range (0-255)
LookupTable = 0 | binary 00000000 CountSetBits 0
LookupTable = 1 | binary 00000001 CountSetBits 1
LookupTable = 1 | binary 00000010 CountSetBits 1
LookupTanle = 2 | binary 00000011 CountSetBits 2
LookupTable = 1 | binary 00000100 CountSetBits 1
and so…on upto LookupTable.
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 LookupTable = 1 LookupTable = 3 so Total bits count : 4
Time Complexity : O(1)
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Count trailing zero bits using lookup table
- Reverse bits using lookup table in O(1) time
- Count set bits in an integer
- Check if bits of a number has count of consecutive set bits in increasing order
- How to swap two bits in a given integer?
- Next greater integer having one more number of set bits
- Previous smaller integer having one less number of set bits
- Find the largest number smaller than integer N with maximum number of set bits
- Count of even set bits between XOR of two arrays
- Count set bits in a range
- Count total bits in a number
- Count unset bits of a number
- Sort an array according to count of set bits | Set 2
- Count pairs (A, B) such that A has X and B has Y number of set bits and A+B = C
- Count total set bits in all numbers from 1 to n | Set 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.