Count set bits in an integer - GeeksforGeeks

01 Mar, 2022
Write an efficient program to count the number of 1s in the 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
 
 
1. Simple Method Loop through all bits in an integer, check if a bit is set and if it is, then increment the set bit count. See the program below. 
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to Count set// bits in an integer#include <bits/stdc++.h>using namespace std; /* Function to get no of set bits in binaryrepresentation of positive integer n */unsigned int countSetBits(unsigned int n){    unsigned int count = 0;    while (n) {        count += n & 1;        n >>= 1;    }    return count;} /* Program to test function countSetBits */int main(){    int i = 9;    cout << countSetBits(i);    return 0;} // This code is contributed// by Akanksha Rai
// C program to Count set// bits in an integer#include <stdio.h> /* Function to get no of set bits in binary   representation of positive integer n */unsigned int countSetBits(unsigned int n){    unsigned int count = 0;    while (n) {        count += n & 1;        n >>= 1;    }    return count;} /* Program to test function countSetBits */int main(){    int i = 9;    printf("%d", countSetBits(i));    return 0;}
// Java program to Count set// bits in an integerimport java.io.*; class countSetBits {    /* Function to get no of set    bits in binary representation    of positive integer n */    static int countSetBits(int n)    {        int count = 0;        while (n > 0) {            count += n & 1;            n >>= 1;        }        return count;    }     // driver program    public static void main(String args[])    {        int i = 9;        System.out.println(countSetBits(i));    }} // This code is contributed by Anshika Goyal.
# Python3 program to Count set# bits in an integer # Function to get no of set bits in binary# representation of positive integer n */def  countSetBits(n):    count = 0    while (n):        count += n & 1        n >>= 1    return count  # Program to test function countSetBits */i = 9print(countSetBits(i)) # This code is contributed by# Smitha Dinesh Semwal
// C# program to Count set// bits in an integerusing System; class GFG {    // Function to get no of set    // bits in binary representation    // of positive integer n    static int countSetBits(int n)    {        int count = 0;        while (n > 0) {            count += n & 1;            n >>= 1;        }        return count;    }     // Driver Code    public static void Main()    {        int i = 9;        Console.Write(countSetBits(i));    }} // This code is contributed by Sam007
<?php// PHP program to Count set// bits in an integer // Function to get no of set // bits in binary representation// of positive integer nfunction countSetBits($n){    $count = 0;    while ($n)    {        $count += $n & 1;        $n >>= 1;    }    return $count;} // Driver Code$i = 9;echo countSetBits($i); // This code is contributed by ajit?>
<script>   // Javascript program to Count set   // bits in an integer    /* Function to get no of set bits in binary   representation of positive integer n */   function countSetBits(n)   {     var count = 0;     while (n)     {       count += n & 1;       n >>= 1;     }     return count;   }    /* Program to test function countSetBits */   var i = 9;   document.write(countSetBits(i));      // This code is contributed by noob2000. </script>
Output : 
2
Time Complexity: Θ(logn) (Theta of logn)
Auxiliary Space: O(1)
Recursive Approach:  
C++
Java
Python3
C#
PHP
Javascript
// cpp implementation of recursive// approach to find the number// of set bits in binary representation// of positive integer n#include <bits/stdc++.h>using namespace std; // recursive function to count set bitsint countSetBits(int n){    // base case    if (n == 0)        return 0;     else         // if last bit set add 1 else add 0        return (n & 1) + countSetBits(n >> 1);} // driver codeint main(){    // get value from user    int n = 9;     // function calling    cout << countSetBits(n);     return 0;} // This code is contributed by Raj.
// Java implementation of recursive// approach to find the number// of set bits in binary representation// of positive integer nimport java.io.*; class GFG {     // recursive function to count set bits    public static int countSetBits(int n)    {         // base case        if (n == 0)            return 0;         else             // if last bit set add 1 else add 0            return (n & 1) + countSetBits(n >> 1);    }     // Driver code    public static void main(String[] args)    {         // get value from user        int n = 9;         // function calling        System.out.println(countSetBits(n));    }} // This code is contributes by sunnysingh
# Python3 implementation of recursive# approach to find the number of set# bits in binary representation of# positive integer n def countSetBits( n):         # base case    if (n == 0):        return 0     else:         # if last bit set add 1 else        # add 0        return (n & 1) + countSetBits(n >> 1)         # Get value from usern = 9 # Function callingprint( countSetBits(n))             # This code is contributed by sunnysingh
// C# implementation of recursive// approach to find the number of// set bits in binary representation// of positive integer nusing System; class GFG {     // recursive function    // to count set bits    public static int countSetBits(int n)    {         // base case        if (n == 0)            return 0;         else             // if last bit set            // add 1 else add 0            return (n & 1) + countSetBits(n >> 1);    }     // Driver code    static public void Main()    {         // get value        // from user        int n = 9;         // function calling        Console.WriteLine(countSetBits(n));    }} // This code is contributed by aj_36
<?php// PHP implementation of recursive// approach to find the number of// set bits in binary representation// of positive integer n // recursive function// to count set bitsfunction countSetBits($n){    // base case    if ($n == 0)        return 0;     else         // if last bit set        // add 1 else add 0        return ($n & 1) +                countSetBits($n >> 1);} // Driver code // get value from user$n = 9; // function callingecho countSetBits($n); // This code is contributed by m_kit.?>
<script> // Javascript implementation of recursive// approach to find the number// of set bits in binary representation// of positive integer n // recursive function to count set bitsfunction countSetBits(n){     // base case    if (n == 0)        return 0;     else         // if last bit set add 1 else add 0        return (n & 1) + countSetBits(n >> 1);} // driver code     // get value from user    let n = 9;     // function calling    document.write(countSetBits(n));  // This code is contributed by Mayank Tyagi</script>
Output : 
2
Time Complexity: O(log n)
Auxiliary Space: O(1)
2. Brian Kernighan’s Algorithm: 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. The beauty of this solution is the number of times it loops is equal to the number of set bits in a given integer. 
   1  Initialize count: = 0
   2  If integer n is not zero
      (a) Do bitwise & with (n-1) and assign the value back to n
          n: = n&(n-1)
      (b) Increment count by 1
      (c) go to step 2
   3  Else return count
Implementation of Brian Kernighan’s Algorithm:  
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to Count set// bits in an integer#include <iostream>using namespace std;class gfg {    /* Function to get no of set bits in binaryrepresentation of passed binary no. */public:    unsigned int countSetBits(int n)    {        unsigned int count = 0;        while (n) {            n &= (n - 1);            count++;        }        return count;    }};/* Program to test function countSetBits */int main(){    gfg g;    int i = 9;    cout << g.countSetBits(i);    return 0;}
// C program to Count set// bits in an integer#include <stdio.h> /* Function to get no of set bits in binary   representation of passed binary no. */unsigned int countSetBits(int n){    unsigned int count = 0;    while (n) {        n &= (n - 1);        count++;    }    return count;} /* Program to test function countSetBits */int main(){    int i = 9;    printf("%d", countSetBits(i));    getchar();    return 0;}
// Java program to Count set// bits in an integerimport java.io.*; class countSetBits {    /* Function to get no of set    bits in binary representation    of passed binary no. */    static int countSetBits(int n)    {        int count = 0;        while (n > 0) {            n &= (n - 1);            count++;        }        return count;    }     // driver program    public static void main(String args[])    {        int i = 9;        System.out.println(countSetBits(i));    }} // This code is contributed by Anshika Goyal.
# Function to get no of set bits in binary# representation of passed binary no. */def countSetBits(n):     count = 0    while (n):        n &= (n-1)        count+= 1         return count  # Program to test function countSetBitsi = 9print(countSetBits(i))  # This code is contributed by# Smitha Dinesh Semwal
// C# program to Count set// bits in an integerusing System; class GFG {     /* Function to get no of set    bits in binary representation    of passed binary no. */    static int countSetBits(int n)    {        int count = 0;        while (n > 0) {            n &= (n - 1);            count++;        }        return count;    }     // Driver Code    static public void Main()    {        int i = 9;        Console.WriteLine(countSetBits(i));    }} // This code is contributed by ajit
<?php /* Function to get no ofset bits in binaryrepresentation of passedbinary no. */function countSetBits($n){    $count = 0;    while ($n)    {    $n &= ($n - 1) ;    $count++;    }    return $count;} // Driver Code$i = 9;echo countSetBits($i); // This code is contributed// by akt_mit?>
<script> // JavaScript program to Count set// bits in an integerclass /* Function to get no of setbits in binary representationof passed binary no. */ function countSetBits(n){    var count = 0;    while (n > 0)    {        n &= (n - 1);        count++;    }    return count;} // driver programvar i = 9;document.write(countSetBits(i)); // This code is contributed by 29AjayKumar </script>
Output : 
2
Example for Brian Kernighan’s Algorithm:  
   n =  9 (1001)
   count = 0

   Since 9 > 0, subtract by 1 and do bitwise & with (9-1)
   n = 9&8  (1001 & 1000)
   n = 8
   count  = 1

   Since 8 > 0, subtract by 1 and do bitwise & with (8-1)
   n = 8&7  (1000 & 0111)
   n = 0
   count = 2

   Since n = 0, return count which is 2 now.
Time Complexity: O(logn)
Recursive Approach:  
C++
Java
Python3
C#
PHP
Javascript
// CPP implementation for recursive// approach to find the number of set// bits using Brian Kernighan’s Algorithm#include <bits/stdc++.h>using namespace std; // recursive function to count set bitsint countSetBits(int n){    // base case    if (n == 0)        return 0;    else        return 1 + countSetBits(n & (n - 1));} // driver codeint main(){    // get value from user    int n = 9;     // function calling    cout << countSetBits(n);     return 0;} // This code is contributed by Raj.
// Java implementation for recursive// approach to find the number of set// bits using Brian Kernighan Algorithmimport java.io.*; class GFG {     // recursive function to count set bits    public static int countSetBits(int n)    {         // base case        if (n == 0)            return 0;        else            return 1 + countSetBits(n & (n - 1));    }     // Driver function    public static void main(String[] args)    {         // get value from user        int n = 9;         // function calling        System.out.println(countSetBits(n));    }} // This code is contributed by sunnysingh
# Python3 implementation for# recursive approach to find# the number of set bits using# Brian Kernighan’s Algorithm # recursive function to count# set bitsdef countSetBits(n):     # base case    if (n == 0):        return 0    else:        return 1 + countSetBits(n & (n - 1))                          # Get value from usern = 9     # function callingprint(countSetBits(n)) # This code is contributed by sunnysingh
// C# implementation for recursive// approach to find the number of set// bits using Brian Kernighan Algorithmusing System; class GFG {     // recursive function    // to count set bits    public static int countSetBits(int n)    {         // base case        if (n == 0)            return 0;        else            return 1 + countSetBits(n & (n - 1));    }     // Driver Code    static public void Main()    {         // get value from user        int n = 9;         // function calling        Console.WriteLine(countSetBits(n));    }} // This code is contributed by aj_36
<?php// PHP implementation for// recursive approach to// find the number of set// bits using Brian// Kernighan’s Algorithm // recursive function to// count set bitsfunction countSetBits($n){    // base case    if ($n == 0)        return 0;    else        return 1 +          countSetBits($n &                      ($n - 1));} // Driver Code // get value from user$n = 9; // function callingecho countSetBits($n);     // This code is contributed by ajit.?>
<script> // Javascript implementation for recursive// approach to find the number of set// bits using Brian Kernighan’s Algorithm // recursive function to count set bitsfunction countSetBits(n){    // base case    if (n == 0)        return 0;    else        return 1 + countSetBits(n & (n - 1));} // driver code// get value from user var n = 9;// function calling document.write(countSetBits(n)); </script>
Output : 
2
3. Using Lookup table: We can count bits in O(1) time using the lookup table.Below is the implementation of the above approach:
C++
Java
Python
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; int BitsSetTable256[256]; // Function to initialise the lookup tablevoid initialize(){     // To initially generate the    // table algorithmically    BitsSetTable256[0] = 0;    for (int i = 0; i < 256; i++)    {        BitsSetTable256[i] = (i & 1) +        BitsSetTable256[i / 2];    }} // Function to return the count// of set bits in nint countSetBits(int n){    return (BitsSetTable256[n & 0xff] +            BitsSetTable256[(n >> 8) & 0xff] +            BitsSetTable256[(n >> 16) & 0xff] +            BitsSetTable256[n >> 24]);} // Driver codeint main(){    // Initialise the lookup table    initialize();    int n = 9;    cout << countSetBits(n);} // This code is contributed by Sanjit_Kumar
// Java implementation of the approachclass GFG {     // Lookup table    static int[] BitsSetTable256 = new int[256];     // Function to initialise the lookup table    public static void initialize()    {         // To initially generate the        // table algorithmically        BitsSetTable256[0] = 0;        for (int i = 0; i < 256; i++) {            BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2];        }    }     // Function to return the count    // of set bits in n    public static int countSetBits(int n)    {        return (BitsSetTable256[n & 0xff]                + BitsSetTable256[(n >> 8) & 0xff]                + BitsSetTable256[(n >> 16) & 0xff]                + BitsSetTable256[n >> 24]);    }     // Driver code    public static void main(String[] args)    {         // Initialise the lookup table        initialize();        int n = 9;        System.out.print(countSetBits(n));    }}
# Python implementation of the approachBitsSetTable256 = [0] * 256 # Function to initialise the lookup tabledef initialize():         # To initially generate the    # table algorithmically    BitsSetTable256[0] = 0    for i in range(256):        BitsSetTable256[i] = (i & 1) + BitsSetTable256[i // 2] # Function to return the count# of set bits in ndef countSetBits(n):    return (BitsSetTable256[n & 0xff] +            BitsSetTable256[(n >> 8) & 0xff] +            BitsSetTable256[(n >> 16) & 0xff] +            BitsSetTable256[n >> 24]) # Driver code # Initialise the lookup tableinitialize()n = 9print(countSetBits(n)) # This code is contributed by SHUBHAMSINGH10
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{     // Lookup table    static int[] BitsSetTable256 = new int[256];     // Function to initialise the lookup table    public static void initialize()    {         // To initially generate the        // table algorithmically        BitsSetTable256[0] = 0;        for (int i = 0; i < 256; i++)        {            BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2];        }    }     // Function to return the count    // of set bits in n    public static int countSetBits(int n)    {        return (BitsSetTable256[n & 0xff]                + BitsSetTable256[(n >> 8) & 0xff]                + BitsSetTable256[(n >> 16) & 0xff]                + BitsSetTable256[n >> 24]);    }     // Driver code    public static void Main(String[] args)    {         // Initialise the lookup table        initialize();        int n = 9;        Console.Write(countSetBits(n));    }} // This code is contributed by 29AjayKumar
<script> // javascript implementation of the approach   var BitsSetTable256 = Array.from({length: 256}, (_, i) => 0); // Function to initialise the lookup tablefunction initialize(){     // To initially generate the    // table algorithmically    BitsSetTable256[0] = 0;    for (var i = 0; i < 256; i++) {        BitsSetTable256[i] = (i & 1) +        BitsSetTable256[parseInt(i / 2)];    }} // Function to return the count// of set bits in nfunction countSetBits(n){    return (BitsSetTable256[n & 0xff]            + BitsSetTable256[(n >> 8) & 0xff]            + BitsSetTable256[(n >> 16) & 0xff]            + BitsSetTable256[n >> 24]);} // Driver code // Initialise the lookup tableinitialize();var n = 9;document.write(countSetBits(n)); // This code is contributed by 29AjayKumar </script>
2
 
We can find one use of counting set bits at Count number of bits to be flipped to convert A to BNote: In GCC, we can directly count set bits using __builtin_popcount(). So we can avoid a separate function for counting set bits. 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to demonstrate __builtin_popcount()#include <iostream>using namespace std; int main(){    cout << __builtin_popcount(4) << endl;    cout << __builtin_popcount(15);     return 0;}
// java program to demonstrate// __builtin_popcount() import java.io.*; class GFG {     // Driver code    public static void main(String[] args)    {         System.out.println(Integer.bitCount(4));        System.out.println(Integer.bitCount(15));    }} // This code is contributed by Raj
# Python3 program to demonstrate __builtin_popcount() print(bin(4).count('1'));print(bin(15).count('1')); # This code is Contributed by mits
// C# program to demonstrate// __builtin_popcount()using System;using System.Linq; class GFG {     // Driver code    public static void Main()    {         Console.WriteLine(Convert.ToString(4, 2).Count(c = > c == '1'));        Console.WriteLine(Convert.ToString(15, 2).Count(c = > c == '1'));    }} // This code is contributed by mits
<?php// PHP program to demonstrate// __builtin_popcount() // Driver code$t = log10(4);$x = log(15, 2);$tt = ceil($t);$xx = ceil($x); echo ($tt), "\n";echo ($xx), "\n"; // This code is contributed// by jit_t?>
<script> // Javascript program to demonstrate// __builtin_popcount() document.write((4).toString(2).split('').  filter(x => x == '1').length + "<br>");document.write((15).toString(2).split('').  filter(x => x == '1').length); </script>
Output : 
1
4
4. Mapping numbers with the bit. It simply maintains a map(or array) of numbers to bits for a nibble. A Nibble contains 4 bits. So we need an array of up to 15. int num_to_bits[16] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4}; Now we just need to get nibbles of a given long/int/word etc recursively.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to count set bits by pre-storing// count set bits in nibbles.#include <bits/stdc++.h>using namespace std; int num_to_bits[16] = { 0, 1, 1, 2, 1, 2, 2, 3,                        1, 2, 2, 3, 2, 3, 3, 4 }; /* Recursively get nibble of a given numberand map them in the array */unsigned int countSetBitsRec(unsigned int num){    int nibble = 0;    if (0 == num)        return num_to_bits[0];     // Find last nibble    nibble = num & 0xf;     // Use pre-stored values to find count    // in last nibble plus recursively add    // remaining nibbles.    return num_to_bits[nibble] + countSetBitsRec(num >> 4);} // Driver codeint main(){    int num = 31;    cout << countSetBitsRec(num);    return 0;} // This code is contributed by rathbhupendra
// C program to count set bits by pre-storing// count set bits in nibbles.#include <stdio.h> int num_to_bits[16] = { 0, 1, 1, 2, 1, 2, 2, 3,                        1, 2, 2, 3, 2, 3, 3, 4 }; /* Recursively get nibble of a given number  and map them in the array  */unsigned int countSetBitsRec(unsigned int num){    int nibble = 0;    if (0 == num)        return num_to_bits[0];     // Find last nibble    nibble = num & 0xf;     // Use pre-stored values to find count    // in last nibble plus recursively add    // remaining nibbles.    return num_to_bits[nibble] + countSetBitsRec(num >> 4);} // Driver codeint main(){    int num = 31;    printf("%d\n", countSetBitsRec(num));}
// Java program to count set bits by pre-storing// count set bits in nibbles. class GFG {    static int[] num_to_bits = new int[] { 0, 1, 1, 2, 1, 2, 2,                                           3, 1, 2, 2, 3, 2, 3, 3, 4 };     /* Recursively get nibble of a given numberand map them in the array */    static int countSetBitsRec(int num)    {        int nibble = 0;        if (0 == num)            return num_to_bits[0];         // Find last nibble        nibble = num & 0xf;         // Use pre-stored values to find count        // in last nibble plus recursively add        // remaining nibbles.        return num_to_bits[nibble] + countSetBitsRec(num >> 4);    }     // Driver code    public static void main(String[] args)    {        int num = 31;        System.out.println(countSetBitsRec(num));    }}// this code is contributed by mits
# Python3 program to count set bits by pre-storing# count set bits in nibbles. num_to_bits =[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]; # Recursively get nibble of a given number# and map them in the arraydef countSetBitsRec(num):    nibble = 0;    if(0 == num):        return num_to_bits[0];         # Find last nibble    nibble = num & 0xf;         # Use pre-stored values to find count    # in last nibble plus recursively add    # remaining nibbles.         return num_to_bits[nibble] + countSetBitsRec(num >> 4);   # Driver code  num = 31;print(countSetBitsRec(num));  # this code is contributed by mits
// C# program to count set bits by pre-storing// count set bits in nibbles. class GFG {    static int[] num_to_bits = new int[16] { 0, 1, 1, 2, 1, 2, 2,                                             3, 1, 2, 2, 3, 2, 3, 3, 4 };     /* Recursively get nibble of a given numberand map them in the array */    static int countSetBitsRec(int num)    {        int nibble = 0;        if (0 == num)            return num_to_bits[0];         // Find last nibble        nibble = num & 0xf;         // Use pre-stored values to find count        // in last nibble plus recursively add        // remaining nibbles.        return num_to_bits[nibble] + countSetBitsRec(num >> 4);    }     // Driver code    static void Main()    {        int num = 31;        System.Console.WriteLine(countSetBitsRec(num));    }}// this code is contributed by mits
<?php// PHP program to count set bits by// pre-storing count set bits in nibbles. $num_to_bits = array(0, 1, 1, 2, 1, 2, 2, 3,                     1, 2, 2, 3, 2, 3, 3, 4); /* Recursively get nibble of a givennumber and map them in the array */function countSetBitsRec( $num){    global $num_to_bits;    $nibble = 0;    if (0 == $num)        return $num_to_bits[0];         // Find last nibble    $nibble = $num & 0xf;         // Use pre-stored values to find count    // in last nibble plus recursively add    // remaining nibbles.    return $num_to_bits[$nibble] +           countSetBitsRec($num >> 4);} // Driver code$num = 31;echo (countSetBitsRec($num)); // This code is contributed by mits?>
<script> // Javascript program to count set bits by pre-storing// count set bits in nibbles.  var num_to_bits =[ 0, 1, 1, 2, 1, 2, 2,                   3, 1, 2, 2, 3, 2, 3, 3, 4 ]; /* Recursively get nibble of a given numberand map them in the array */function countSetBitsRec(num){    var nibble = 0;    if (0 == num)        return num_to_bits[0];     // Find last nibble    nibble = num & 0xf;     // Use pre-stored values to find count    // in last nibble plus recursively add    // remaining nibbles.    return num_to_bits[nibble] + countSetBitsRec(num >> 4);} // Driver codevar num = 31;document.write(countSetBitsRec(num)); // This code is contributed by 29AjayKumar </script>
Output : 
5
Time Complexity: O(log n), because we have log(16, n) levels of recursion.Storage Complexity: O(1) Whether the given number is short, int, long, or long long we require an array of 16 sizes only, which is constant.
5. Checking each bit in a number: 
Each bit in the number is checked for whether it is set or not. The number is bitwise AND with powers of 2, so if the result is not equal to zero, we come to know that the particular bit in the position is set.
C
C++
Java
Python3
C#
Javascript
#include <stdio.h> // Check each bit in a number is set or not// and return the total count of the set bits.int countSetBits(int N){    int count = 0;       // (1 << i) = pow(2, i)    for (int i = 0; i < sizeof(int) * 8; i++) {        if (N & (1 << i))            count++;    }    return count;} // Driver Codeint main(){    int N = 15;     printf("%d", countSetBits(N));    return 0;}
#include <iostream>using namespace std; // Check each bit in a number is set or not// and return the total count of the set bits.int countSetBits(int N){    int count = 0;    // (1 << i) = pow(2, i)    for (int i = 0; i < sizeof(int) * 8; i++) {        if (N & (1 << i))            count++;    }    return count;} int main(){     int N = 15;     cout << countSetBits(N) << endl;    return 0;}
public class GFG{     // Check each bit in a number is set or not  // and return the total count of the set bits.  static int countSetBits(int N)  {    int count = 0;    // (1 << i) = pow(2, i)    for (int i = 0; i < 4 * 8; i++)    {      if ((N & (1 << i)) != 0)        count++;    }    return count;  }   // Driver code  public static void main(String[] args)  {    int N = 15;    System.out.println(countSetBits(N));  }} // This code is contributed by divyeshrabadiya07.
# Check each bit in a number is set or not# and return the total count of the set bitsdef countSetBits(N):  count = 0   # (1 << i) = pow(2, i)  for i in range(4*8):    if(N & (1 << i)):      count += 1      return count     # Driver code    N = 15    print(countSetBits(N))     # This code is contributed by avanitrachhadiya2155
using System;class GFG{   // Check each bit in a number is set or not  // and return the total count of the set bits.  static int countSetBits(int N)  {    int count = 0;     // (1 << i) = pow(2, i)    for (int i = 0; i < 4 * 8; i++)    {      if ((N & (1 << i)) != 0)        count++;    }    return count;  }   // Driver code  static void Main()  {    int N = 15;    Console.WriteLine(countSetBits(N));  }} // This code is contributed by divyesh072019.
<script>     // Check each bit in a number is set or not  // and return the total count of the set bits.  function countSetBits(N)  {      var count = 0;    // (1 << i) = pow(2, i)    for (i = 0; i < 4 * 8; i++)    {        if ((N & (1 << i)) != 0)        count++;    }    return count;  }   // Driver code  var N = 15;  document.write(countSetBits(N)); // This code is contributed by Amit Katiyar</script>
4
Count set bits in an integer Using Lookup Table
 
Sam007
jit_t
R_Raj
NileshAwate
BabisSarantoglou
Mithun Kumar
Akanksha_Rai
SoumikMondal
rathbhupendra
likeicare
Ankitkashyap
Sanjit_Prasad
SHUBHAMSINGH10
29AjayKumar
paulsonraja
divyeshrabadiya07
divyesh072019
avanitrachhadiya2155
rutvik_56
noob2000
mayanktyagi1709
amit143katiyar
ytxmobile
rishavmahato348
subham348
Adobe
Brocade
Cisco
Juniper Networks
Qualcomm
Samsung
setBitCount
Wipro
Bit Magic
Samsung
Adobe
Wipro
Brocade
Juniper Networks
Cisco
Qualcomm
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Cyclic Redundancy Check and Modulo-2 Division
Add two numbers without using arithmetic operators
Set, Clear and Toggle a given bit of a number in C
Bit Fields in C
Bits manipulation (Important tactics)
Find the element that appears once
Divide two integers without using multiplication, division and mod operator
C++ bitset and its application
1's and 2's complement of a Binary Number
Check whether K-th bit is set or not