Count set bits in an integer

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 11 is 1101 and has 3 set bits

setbit



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 below program.

C

#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

// Java program to Count set
// bits in an integer 
import 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

# 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 = 9
print(countSetBits(i))
  
# This code is contributed by
# Smitha Dinesh Semwal

C#

// C# program to Count set
// bits in an integer 
using 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
// Function to get no of set  
// bits in binary representation 
// of positive integer n 
function 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
?>


Output :

2

Time Complexity: (-)(logn) (Theta of logn)

Recursive Approach :

C++

// 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 bits
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
int main()
{
    // get value from user
    int n = 9;
  
    // function calling
    cout << countSetBits(n);
  
    return 0;
}
  
// This code is contributed by Raj.

Java

// Java implementation of recursive
// approach to find the number
// of set bits in binary representation
// of positive integer n
import 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

# 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 user
n = 9
  
# Function calling
print( countSetBits(n))     
          
# This code is contributed by sunnysingh

C#

// C# implementation of recursive
// approach to find the number of 
// set bits in binary representation
// of positive integer n
using 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
// PHP implementation of recursive
// approach to find the number of 
// set bits in binary representation
// of positive integer n
  
// recursive function 
// to count set bits
function 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 calling
echo countSetBits($n);
  
// This code is contributed by m_kit.
?>


Output :

2

2. Brian Kernighan’s Algorithm:
Subtraction of 1 from a number toggles all the bits (from right to left) till the rightmost set bit(including the rightmost set bit). So if we subtract a number by 1 and do bitwise & with itself (n & (n-1)), we unset the rightmost set bit. If we do n & (n-1) in a loop and count the no of times 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

#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

// Java program to Count set 
// bits in an integer 
import 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.

Python3

# 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 countSetBits 
i = 9
print(countSetBits(i))
   
# This code is contributed by
# Smitha Dinesh Semwal

C#

// C# program to Count set 
// bits in an integer
using 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

<?php
  
/* Function to get no of 
set bits in binary
representation of passed 
binary 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
?>


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++

// 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 bits
int countSetBits(int n)
{
    // base case
    if (n == 0)
        return 0;
    else
        return 1 + countSetBits(n & (n - 1));
}
  
// driver code 
int main()
{
    // get value from user
    int n = 9;
      
    // function calling
    cout << countSetBits(n);
      
    return 0;
}
  
// This code is contributed by Raj.

Java

// Java implementation for recursive
// approach to find the number of set
// bits using Brian Kernighan Algorithm
import 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

# Python3 implementation for
# recursive approach to find
# the number of set bits using
# Brian Kernighan’s Algorithm
  
# recursive function to count
# set bits
def countSetBits(n):
  
    # base case
    if (n == 0):
        return 0
    else:
        return 1 + countSetBits(n & (n - 1))
              
              
# Get value from user
n = 9
      
# function calling
print(countSetBits(n))
  
# This code is contributed by sunnysingh

C#

// C# implementation for recursive
// approach to find the number of set
// bits using Brian Kernighan Algorithm
using 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
// PHP implementation for 
// recursive approach to 
// find the number of set
// bits using Brian 
// Kernighan’s Algorithm
  
// recursive function to
// count set bits
function 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 calling
echo countSetBits($n);
      
// This code is contributed by ajit.
?>


Output :

2

3. Using Lookup table: We can count bits in O(1) time using lookup table. Please see http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable for details.

We can find one use of counting set bits at Count number of bits to be flipped to convert A to B

Note: In GCC, we can directly count set bits using __builtin_popcount(). So we can avoid a separate function for counting set bits.

C++

// C++ program to demonstrate __builtin_popcount()
#include <iostream>
using namespace std;
  
int main()
{
   cout << __builtin_popcount (4) << endl;
   cout << __builtin_popcount (15);
  
   return 0;
}

PHP

<?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
?>


Output :

1
4

Count set bits in an integer Using Lookup Table

References:
http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive



My Personal Notes arrow_drop_up


Improved By : Sam007, jit_t