[Naive Approach] One by One Counting - O(log n) Time and O(1) Space
One by one process every bit starting from the least significant. Check if current bit is set using (n & 1). If it is set, increment the count. Then right shift the number by one position and repeat the process until the number becomes 0.
C++
#include<iostream>usingnamespacestd;intsetBits(intn){intcnt=0;// Traverse all bits of the number.while(n>0){// If the last bit is set, increment the count.if(n&1)cnt++;// Move to the next bit.n>>=1;}returncnt;}intmain(){intn=8;cout<<setBits(n);return0;}
Java
publicclassGFG{publicstaticintsetBits(intn){intcnt=0;// Traverse all bits of the number.while(n>0){// If the last bit is set, increment the count.if((n&1)==1)cnt++;// Move to the next bit.n>>=1;}returncnt;}publicstaticvoidmain(String[]args){intn=8;System.out.println(setBits(n));}}
Python
defsetBits(n):cnt=0# Traverse all bits of the number.whilen>0:# If the last bit is set, increment the count.ifn&1:cnt+=1# Move to the next bit.n>>=1returncntif__name__=='__main__':n=8print(setBits(n))
C#
usingSystem;publicclassGFG{publicstaticintsetBits(intn){intcnt=0;// Traverse all bits of the number.while(n>0){// If the last bit is set, increment the count.if((n&1)==1)cnt++;// Move to the next bit.n>>=1;}returncnt;}publicstaticvoidMain(){intn=8;Console.WriteLine(setBits(n));}}
JavaScript
functionsetBits(n){letcnt=0;// Traverse all bits of the number.while(n>0){// If the last bit is set, increment the count.if(n&1)cnt++;// Move to the next bit.n>>=1;}returncnt;}// Driver Codeconstn=8;console.log(setBits(n));
Output
1
[Expected Approach] Using Brian Kernighan's Algorithm - O(log n) Time and O(1) Space
The idea is to repeatedly remove the rightmost set bit from the number using the expression n = n & (n - 1). Since each operation removes exactly one set bit, the loop executes only once for every set bit only.
%he key operation is n &= (n - 1), which removes the least significant set bit from n. Each time this is done, it means one set bit has been counted and removed. Let us understand this with an example.
Subtracting 1 from a decimal number flips all the bits after the rightmost set bit(which is 1) including the rightmost set bit. for example : 10 in binary is 00001010 9 in binary is 00001001 8 in binary is 00001000 7 in binary is 00000111 So if we subtract a number by 1 and do it bitwise & with itself (n & (n-1)), we unset the rightmost set bit. If we do n & (n-1) in a loop and count the number of times the loop executes, we get the set bit count.
Let us understand complete algorithm with an example:
Initially, n = 8 whose binary representation is 1000, and cnt = 0.
In the first iteration, n = n & (n - 1) = 1000 & 0111 = 0000, so the rightmost (and only) set bit is removed.
Increment cnt to 1. Now n becomes 0, so the loop terminates.
The final value of cnt is 1, which is the number of set bits in 8.
C++
#include<iostream>usingnamespacestd;intsetBits(intn){intcnt=0;// Continue until all set bits are removed.while(n>0){// Remove the rightmost set bit.n=n&(n-1);// Increment the count.cnt++;}returncnt;}intmain(){intn=8;cout<<setBits(n);return0;}
Java
publicclassGFG{intsetBits(intn){intcnt=0;// Continue until all set bits are removed.while(n>0){// Remove the rightmost set bit.n=n&(n-1);// Increment the count.cnt++;}returncnt;}publicstaticvoidmain(String[]args){GFGobj=newGFG();intn=8;System.out.println(obj.setBits(n));}}
Python
defsetBits(n):cnt=0# Continue until all set bits are removed.whilen>0:# Remove the rightmost set bit.n=n&(n-1)# Increment the count.cnt+=1returncntif__name__=="__main__":n=8print(setBits(n))
C#
usingSystem;publicclassGFG{publicintsetBits(intn){intcnt=0;// Continue until all set bits are removed.while(n>0){// Remove the rightmost set bit.n=n&(n-1);// Increment the count.cnt++;}returncnt;}publicstaticvoidMain(){GFGobj=newGFG();intn=8;Console.WriteLine(obj.setBits(n));}}
JavaScript
functionsetBits(n){letcnt=0;// Continue until all set bits are removed.while(n>0){// Remove the rightmost set bit.n=n&(n-1);// Increment the count.cnt++;}returncnt;}// Driver Codeletn=8;console.log(setBits(n));
Output
1
[Alternate Approach - 1] Using Lookup Table - O(1) Time and O(1) Space
The idea is to precompute the number of set bits for all possible 8-bit values (0 to 255) and store them in a lookup table. Then divide the given integer into four 8-bit parts (bytes) and use the lookup table to obtain the set bit count for each byte. The final answer is the sum of these four values.
Working of Approach:
Precompute the number of set bits for all 256 possible 8-bit values (0 to 255) and store them in a lookup table.
Divide the given integer into four 8-bit parts (bytes) using bitwise operations.
Retrieve the set bit count of each byte directly from the lookup table and add them together.
C++
#include<iostream>usingnamespacestd;inttable[256];// Precompute set bits for all 8-bit numbers.voidinitialize(){table[0]=0;for(inti=1;i<256;i++)table[i]=(i&1)+table[i/2];}intsetBits(intn){initialize();// Sum the set bits in all four bytes.returntable[n&0xff]+table[(n>>8)&0xff]+table[(n>>16)&0xff]+table[(n>>24)&0xff];}intmain(){intn=8;cout<<setBits(n);return0;}
Java
publicclassGFG{staticinttable[]=newint[256];// Precompute set bits for all 8-bit numbers.staticvoidinitialize(){table[0]=0;for(inti=1;i<256;i++)table[i]=(i&1)+table[i/2];}staticintsetBits(intn){initialize();// Sum the set bits in all four bytes.returntable[n&0xff]+table[(n>>8)&0xff]+table[(n>>16)&0xff]+table[(n>>24)&0xff];}publicstaticvoidmain(String[]args){intn=8;System.out.println(setBits(n));}}
Python
# Precompute set bits for all 8-bit numbers.table=[0]*256definitialize():table[0]=0foriinrange(1,256):table[i]=(i&1)+table[i//2]defsetBits(n):initialize()# Sum the set bits in all four bytes.return(table[n&0xff]+table[(n>>8)&0xff]+table[(n>>16)&0xff]+table[(n>>24)&0xff])if__name__=="__main__":n=8print(setBits(n))
C#
usingSystem;publicclassGFG{staticint[]table=newint[256];// Precompute set bits for all 8-bit numbers.staticvoidinitialize(){table[0]=0;for(inti=1;i<256;i++)table[i]=(i&1)+table[i/2];}staticintsetBits(intn){initialize();// Sum the set bits in all four bytes.returntable[n&0xff]+table[(n>>8)&0xff]+table[(n>>16)&0xff]+table[(n>>24)&0xff];}publicstaticvoidMain(){intn=8;Console.WriteLine(setBits(n));}}
JavaScript
lettable=newArray(256).fill(0);// Precompute set bits for all 8-bit numbers.functioninitialize(){table[0]=0;for(leti=1;i<256;i++)table[i]=(i&1)+table[Math.floor(i/2)];}functionsetBits(n){initialize();// Sum the set bits in all four bytes.returntable[n&0xff]+table[(n>>8)&0xff]+table[(n>>16)&0xff]+table[(n>>24)&0xff];}// Driver Codeletn=8;console.log(setBits(n));
Output
1
[Alternate Approach - 2] Using Mapping Nibbles - O(1) Time and O(1) Space
The idea is to precompute the number of set bits for all possible 4-bit values (nibbles). Since each nibble can have only 16 possible values (0 to 15), we store their set bit counts in a small array. Then, repeatedly extract the last nibble of the number using n & 15, add its set bit count from the table, and right shift the number by 4 bits until it becomes 0.
Working of Approach:
Store the number of set bits for all 16 possible 4-bit values (0 to 15) in a lookup table.
Extract the last 4 bits (one nibble) of the number using n & 15 and add its set bit count from the lookup table.
Right shift the number by 4 bits to process the next nibble and repeat until the number becomes 0.
The accumulated count gives the total number of set bits in the given integer.
C++
#include<iostream>usingnamespacestd;intsetBits(intn){// Lookup table for all possible 4-bit values.inttable[16]={0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};intcnt=0;// Process one nibble (4 bits) at a time.while(n>0){// Add the set bits in the last nibble.cnt+=table[n&15];// Remove the processed nibble.n>>=4;}returncnt;}intmain(){intn=8;cout<<setBits(n);return0;}
Java
publicclassGFG{// Lookup table for all possible 4-bit values.privatestaticfinalint[]table={0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};publicstaticintsetBits(intn){intcnt=0;// Process one nibble (4 bits) at a time.while(n>0){// Add the set bits in the last nibble.cnt+=table[n&15];// Remove the processed nibble.n>>=4;}returncnt;}publicstaticvoidmain(String[]args){intn=8;System.out.println(setBits(n));}}
Python
defsetBits(n):# Lookup table for all possible 4-bit values.table=[0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4]cnt=0# Process one nibble (4 bits) at a time.whilen>0:# Add the set bits in the last nibble.cnt+=table[n&15]# Remove the processed nibble.n>>=4returncntif__name__=='__main__':n=8print(setBits(n))
C#
usingSystem;classGFG{// Lookup table for all possible 4-bit values.privatestaticreadonlyint[]table={0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};publicstaticintsetBits(intn){intcnt=0;// Process one nibble (4 bits) at a time.while(n>0){// Add the set bits in the last nibble.cnt+=table[n&15];// Remove the processed nibble.n>>=4;}returncnt;}staticvoidMain(){intn=8;Console.WriteLine(setBits(n));}}
JavaScript
functionsetBits(n){// Lookup table for all possible 4-bit values.consttable=[0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4];letcnt=0;// Process one nibble (4 bits) at a time.while(n>0){// Add the set bits in the last nibble.cnt+=table[n&15];// Remove the processed nibble.n>>=4;}returncnt;}// Driver Codeconstn=8;console.log(setBits(n));
Output
1
[Alternate Approach - 3] Using Library Function (Quick Syntax) - O(1) Time and O(1) Space
The idea is to use the compiler's built-in function that directly returns the number of set bits in an integer. These functions are highly optimized and often map to a single hardware instruction (such as POPCNT) on supported processors.
Different language/compiler-provided built-in function:
C++
Library Function: __builtin_popcount(n)
Note: Available in GCC and Clang compilers. For long long, use __builtin_popcountll(n).
Java
Library Function: Integer.bitCount(n)
Note: Available in the Java Standard Library.
Python
Library Function: n.bit_count()
Note: Available from Python 3.10 onwards.
C#
Library Function: BitOperations.PopCount((uint)n)
Note: Available in System.Numerics (.NET Core 3.0+ / .NET 5+).
JavaScript
Quick Syntax: n.toString(2).split('1').length - 1
Note: JavaScript does not provide a built-in popcount function, so this is a concise alternative using the binary string representation.
C++
#include<iostream>usingnamespacestd;intsetBits(intn){// Returns the number of set bits.return__builtin_popcount(n);}intmain(){intn=8;cout<<setBits(n);return0;}
Java
classGFG{publicstaticintsetBits(intn){// Returns the number of set bits.returnInteger.bitCount(n);}publicstaticvoidmain(String[]args){intn=8;System.out.println(setBits(n));}}
Python
defsetBits(n):# Returns the number of set bits.returnbin(n).count('1')if__name__=='__main__':n=8print(setBits(n))
C#
usingSystem;usingSystem.Numerics;classGFG{publicstaticintSetBits(intn){// Returns the number of set bits.returnBitOperations.PopCount((uint)n);}staticvoidMain(){intn=8;Console.WriteLine(SetBits(n));}}
JavaScript
functionsetBits(n){// Returns the number of set bits.returnn.toString(2).split("0").join("").length;}// Driver Codeletn=8;console.log(setBits(n));