The Wayback Machine - https://web.archive.org/web/20240926161139/https://www.geeksforgeeks.org/count-set-bits-in-an-integer/
Open In App

Count set bits in an integer

Last Updated : 11 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Easy
76.5%
1.4L
 

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

 

setbit

 

Recommended Practice

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++ program to Count set
// bits in an integer
#include <bits/stdc++.h>
using namespace std;
 
/* 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;
    cout << countSetBits(i);
    return 0;
}
 
// This code is contributed
// by Akanksha Rai


C




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




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




# 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 = 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
// PHP 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)
{
    $count = 0;
    while ($n)
    {
        $count += $n & 1;
        $n >>= 1;
    }
    return $count;
}
 
// Driver Code
$i = 9;
echo countSetBits($i);
 
// This code is contributed by ajit
?>


Javascript




<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: O(log n) 
Auxiliary Space: O(1)

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()
{
    int n = 9;
    // function calling
    cout << countSetBits(n);
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta (kriSania804)


C




// cpp implementation of recursive approach to find the
// number of set bits in binary representation of positive
// integer n
#include <stdio.h>
 
// 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()
{
    int n = 9;
    // function calling
    printf("%d", countSetBits(n));
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta (kriSania804)


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


Javascript




<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 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
    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(log n) for recursive stack space

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

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.

Implementation of Brian Kernighan’s Algorithm:  

C++




// C++ program to Count set
// bits in an integer
#include <iostream>
using namespace std;
class gfg {
    /* Function to get no of set bits in binary
representation 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




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




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


Javascript




<script>
 
// JavaScript program to Count set
// bits in an integerclass
 
/* Function to get no of set
bits in binary representation
of passed binary no. */
 
function countSetBits(n)
{
    var count = 0;
    while (n > 0)
    {
        n &= (n - 1);
        count++;
    }
    return count;
}
 
// driver program
var i = 9;
document.write(countSetBits(i));
 
// This code is contributed by 29AjayKumar
 
</script>


Output

2

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

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


Javascript




<script>
 
// Javascript 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
 
var n = 9;
// function calling
 
document.write(countSetBits(n));
 
</script>


Output

2

Time Complexity: O(log n)
Auxiliary Space: O(log n)

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




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
int BitsSetTable256[256];
 
// Function to initialise the lookup table
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
int countSetBits(int n)
{
    return (BitsSetTable256[n & 0xff] +
            BitsSetTable256[(n >> 8) & 0xff] +
            BitsSetTable256[(n >> 16) & 0xff] +
            BitsSetTable256[n >> 24]);
}
 
// Driver code
int main()
{
    // Initialise the lookup table
    initialize();
    int n = 9;
    cout << countSetBits(n);
}
 
// This code is contributed by Sanjit_Kumar


Java




// Java implementation of the approach
import java.util.*;
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;
        System.out.print(countSetBits(n));
    }
}


Python




# Python implementation of the approach
BitsSetTable256 = [0] * 256
 
# Function to initialise the lookup table
def 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 n
def countSetBits(n):
    return (BitsSetTable256[n & 0xff] +
            BitsSetTable256[(n >> 8) & 0xff] +
            BitsSetTable256[(n >> 16) & 0xff] +
            BitsSetTable256[n >> 24])
 
# Driver code
 
# Initialise the lookup table
initialize()
n = 9
print(countSetBits(n))
 
# This code is contributed by SHUBHAMSINGH10


C#




// C# implementation of the approach
using 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


Javascript




<script>
 
// javascript implementation of the approach  
 
var BitsSetTable256 = Array.from({length: 256}, (_, i) => 0);
 
// Function to initialise the lookup table
function 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 n
function countSetBits(n)
{
    return (BitsSetTable256[n & 0xff]
            + BitsSetTable256[(n >> 8) & 0xff]
            + BitsSetTable256[(n >> 16) & 0xff]
            + BitsSetTable256[n >> 24]);
}
 
// Driver code
 // Initialise the lookup table
initialize();
var n = 9;
document.write(countSetBits(n));
 
// This code is contributed by 29AjayKumar
 
</script>


Output

2

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

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;
}


Java




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




print(bin(4).count('1'));
print(bin(15).count('1'));
 
# This code is Contributed by mits


C#




using System;
 
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Convert.ToString(4, 2).Replace("0", "").Length);
        Console.WriteLine(Convert.ToString(15, 2).Replace("0", "").Length);
    }
}


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


Javascript




<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

Time complexity: O(1)
Auxiliary space: O(1)

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++ 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 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 code
int main()
{
    int num = 31;
    cout << countSetBitsRec(num);
    return 0;
}
 
// This code is contributed by rathbhupendra


C




// 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 code
int main()
{
    int num = 31;
    printf("%d\n", countSetBitsRec(num));
}


Java




// Java program to count set bits by pre-storing
// count set bits in nibbles.
import java.util.*;
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 number
and 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




# 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 array
def 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#




// 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 number
and 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
// 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 given
number 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
?>


Javascript




<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 number
and 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 code
var 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




#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 Code
int main()
{
    int N = 15;
 
    printf("%d", countSetBits(N));
    return 0;
}


C++




#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;
}


Java




import java.util.*;
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.


Python3




# Check each bit in a number is set or not
# and return the total count of the set bits
 
 
def 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


C#




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.


Javascript




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


Output

4

Time complexity: O(log n)
Auxiliary space: O(1)

6. Using power of 2:(efficient method to find for large value also)

Iterate from k to 0 , where k is the largest power of 2 such that pow(2, k) <= num . And check if the Bitwise AND of num and pow(2, i) is greater than zero or not. If it is greater than zero , Then i-th bit is set ,then increase the count by 1.

C++




// C++ implementation of the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find largest power of 2 such that
// pow(2,k) <= N
int findk(int n)
{ int k; int i=0; int val=pow(2,i);
   
 while(val<=n)
 {
     k=i; i++;
    val=pow(2,i);
 }
  return k;
}
 
// Function to count set bits in a number
int countSetBits(int N)
{
    int count = 0;
    int k=findk(N);
    int val , x;
   
    // Iterating from largest power to 2 such that
    // pow(2,k) to 0
    for (int i = k; i >= 0; i--)
    {
        val=pow(2,i);
        x=val & N; //x will store Bitwise AND of N & val
       
       if(x > 0)
       { count++;
       }
    }
    return count;//return count of set bits
}
 
// Drive Code
int main()
{
    int N = 15;
     
    // Function call
    cout << countSetBits(N) << endl;
    return 0;
}
 
// This code is contributed by nikhilsainiofficial546


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
// import java.lang.Math;
 
public class GFG {
    // Function to find largest power of 2 such that
    // pow(2,k) <= N
    static int findk(int n)
    {
        int k = 0;
        int i = 0;
        int val = (int)Math.pow(2, i);
 
        while (val <= n) {
            k = i;
            i++;
            val = (int)Math.pow(2, i);
        }
        return k;
    }
 
    // Function to count set bits in a number
    static int countSetBits(int N)
    {
        int count = 0;
        int k = findk(N);
        int val, x;
 
        // Iterating from largest power to 2 such that
        // pow(2,k) to 0
        for (int i = k; i >= 0; i--) {
            val = (int)Math.pow(2, i);
            x = val
                & N; // x will store Bitwise AND of N & val
 
            if (x > 0) {
                count++;
            }
        }
        return count; // return count of set bits
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int N = 15;
 
        // Function call
        System.out.println(countSetBits(N));
    }
}


Python3




# Python implementation of the above approach
import math
 
# Function to find largest power of 2 such that
# pow(2,k) <= N
def findk(n):
    i = 0
    val = math.pow(2, i)
    while val <= n:
        k = i
        i += 1
        val = math.pow(2, i)
    return k
 
# Function to count set bits in a number
def countSetBits(N):
    count = 0
    k = findk(N)
    for i in range(k, -1, -1):
        val = int(math.pow(2, i))
        x = val & N # x will store Bitwise AND of N & val
        if x > 0:
            count += 1
    return count
 
# Drive Code
if __name__ == '__main__':
    N = 15
 
    # Function call
    print(countSetBits(N))


C#




using System;
 
class Program
{
    // Function to find largest power of 2 such that
    // pow(2,k) <= N
    static int FindK(int n)
    {
        int k = 0;
        int i = 0;
        int val = (int)Math.Pow(2, i);
 
        while (val <= n)
        {
            k = i;
            i++;
            val = (int)Math.Pow(2, i);
        }
        return k;
    }
 
    // Function to count set bits in a numnber
    static int CountSetBits(int N)
    {
        int count = 0;
        int k = FindK(N);
        int val, x;
 
        // Iterating from largest power to 2 such that
        // pow(2,k) to 0
        for (int i = k; i >= 0; i--)
        {
            val = (int)Math.Pow(2, i);
            x = val & N; //x will store Bitwise AND of N & val
 
            if (x > 0)
            {
                count++;
            }
        }
        return count; //return count of set bits
    }
 
    // Drive Code
    static void Main()
    {
        int N = 15;
 
        // Function call
        Console.WriteLine(CountSetBits(N));
    }
}
//this code is contributed by ajay


Javascript




// JavaScript implementation of the above approach
// function to find largest power of 2 such that
// pow(2,k) <= N
function findk(n){
    let k;
    let i = 0;
    let val = Math.pow(2,i);
    while(val <= n){
        k=i;
        i++;
        val = Math.pow(2,i);
    }
    return k;
}
 
// function to count set bits in a number
function countSetBits(N){
    let count = 0;
    let k = findk(N);
    let val;
    let x;
     
    // iterating from largest power to 2 such that
    // pow(2,k) to 0
    for(let i = k; i>=0; i--){
        val = Math.pow(2,i);
        x = val & N; // x will store bitwise and of N and val
         
        if(x > 0) count++;
    }
    return count; // return count of set bits
}
 
// driver program
let N = 15;
 
// function call
console.log(countSetBits(N));
 
// THIS CODE IS CONTRIUBTED BY KIRTI AGARWAL(KIRTIAGARWAL23121999)


Output

4

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

 

Count set bits in an integer Using Lookup Table



Previous Article
Next Article

Similar Reads

Count of pairs {X, Y} from an array such that sum of count of set bits in X ⊕ Y and twice the count of set bits in X & Y is M
Given an array arr[] consisting of N non-negative integers and an integer M, the task is to find the count of unordered pairs {X, Y} of array elements that satisfies the condition setBits(X ⊕ Y) + 2 * setBits(X & Y) = M, where ⊕ denotes the Bitwise XOR and & denotes the Bitwise AND. Examples: Input: arr[] = {30, 0, 4, 5 }, M = 2Output: 2Exp
14 min read
Flip bits of the sum of count of set bits of two given numbers
Given two numbers A and B, the task is to count the number of set bits in A and B and flip the bits of the obtained sum. Examples: Input: A = 5, B = 7Output: 2Explanation:Binary representation of A is 101.Binary representation of B is 111.Count of set bits in A and B = 2 + 3 = 5.Binary representation of the sum obtained = 101Flipping the bits of th
5 min read
Check if bits of a number has count of consecutive set bits in increasing order
Given a integer n > 0, the task is to find whether in the bit pattern of integer count of continuous 1's are in increasing from left to right. Examples : Input:19 Output:Yes Explanation: Bit-pattern of 19 = 10011, Counts of continuous 1's from left to right are 1, 2 which are in increasing order. Input : 183 Output : yes Explanation: Bit-pattern
11 min read
Count set bits in an integer using Lookup Table
Write an efficient program to count number of 1s in 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 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 t
6 min read
Minimize cost of swapping set bits with unset bits in a given Binary string
Given a binary string S of size N, the task is to find the minimum cost by swapping every set bit with an unset bit such that the cost of swapping pairs of bits at indices i and j is abs(j - i). Note: A swapped bit can't be swapped twice and the count of set bit in the given binary string is at most N/2. Examples: Input: S = "1010001"Output: 3Expla
12 min read
Print numbers having first and last bits as the only set bits
Given a positive integer n. The problem is to print numbers in the range 1 to n having first and last bits as the only set bits.Examples: Input : n = 10 Output : 1 3 5 9 (1)10 = (1)2. (3)10 = (11)2. (5)10 = (101)2. (9)10 = (1001)2 Naive Approach: Print "1". Now for i = 3 to n, check if (i-1) is a Perfect power of two or not. If true then print i. C
10 min read
Find the largest number smaller than integer N with maximum number of set bits
Given an integer N, the task is to find the largest number smaller than N having the maximum number of set bits.Examples: Input : N = 345 Output : 255 Explanation: 345 in binary representation is 101011001 with 5 set bits, and 255 is 11111111 with maximum number of set bits less than the integer N.Input : N = 2 Output : 1 Explanation: 2 in binary r
8 min read
Minimum integer with at most K bits set such that their bitwise AND with N is maximum
Given an integer N which can be represented in 32 bit, the task is to find another integer X that has at most K bits set in its binary representation and bitwise AND of X and N is maximum. Examples: Input: N = 5, K = 1 Output: X = 2 Explanation: Binary representation of 5 is 101, the possible value of X such that it maximize the AND is 2 5 -> 10
7 min read
Next greater integer having one more number of set bits
Given a positive integer 'n' having 'x' number of set bits in its binary representation. The problem is to find the next greater integer(smallest integer greater than n), having (x+1) number of set bits in its binary representation.Examples : Input : 10 Output : 11 (10)10 = (1010)2 is having 2 set bits. (11)10 = (1011)2 is having 3 set bits and is
6 min read
Previous smaller integer having one less number of set bits
Given a positive integer ‘n’ having ‘x’ number of set bits in its binary representation. The problem is to find the previous smaller integer(greatest integer smaller than n), having (x-1) number of set bits in its binary representation.Note: 1 <= n Examples : Input : 8 Output : 0 (8)10 = (1000)2 is having 1 set bit. (0)10 = (0)2 is having 0 set
4 min read
Toggle bits of a number except first and last bits
Given a number, the task is to toggle bits of the number except the first and the last bit.Examples: Input : 10 Output : 12 Binary representation:- 1 0 1 0 After toggling first and last : 1 1 0 0 Input : 9 Output : 15 Binary representation : 1 0 0 1 After toggling first and last : 1 1 1 1 Prerequisite: Find most significant set bit of a number Gene
8 min read
Check if all bits can be made same by flipping two consecutive bits
Given a binary string, the task is to find whether all the digits of the string can be made equal i.e either 0 or 1 by flipping two consecutive bits any number of times.Examples: Input: 01011Output: YESExplanation:Flip 2nd and 3rd bit -> 00111, again flipping 1'st and 2'nd bit -> 11111 Input: 100011Output: NOExplanation:No number of moves can
5 min read
Count positions in Binary Matrix having equal count of set bits in corresponding row and column
Given a boolean matrix mat[][] of size M * N, the task is to print the count of indices from the matrix whose corresponding row and column contain an equal number of set bits. Examples: Input; mat[][] = {{0, 1}, {1, 1}}Output: 2Explanation:Position (0, 0) contains 1 set bit in corresponding row {(0, 0), (0, 1)} and column {(0, 0), (1, 0)}.Position
10 min read
Reverse bits of a positive integer number in Python
Given an positive integer and size of bits, reverse all bits of it and return the number with reversed bits.Examples: Input : n = 1, bitSize=32 Output : 2147483648 On a machine with size of bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648, bitSize=32 Output : 1 We can solve this problem quickly in Python. Approach is very simple,
4 min read
Maximize given integer by swapping pairs of unequal bits
Given a positive integer N, the task is to determine the maximum possible integer that can be formed by performing the following operations on the given integer N: Convert the integer into its binary representation.Swap only unequal bits in its binary representation. Examples: Input : 11Output : 14Explanation : (11)10 = (1011)2Swap 0th bit with 2nd
7 min read
Maximizing Unset Bits in Integer with Constraints
Given a non-negative integer n. You are only allowed to make a set bit unset, the task is to find the maximum possible value of the query so that after performing the given operations, no three consecutive bits of the integer query are set bits. Examples: Input: n = 2Output: 2Explanation: 2's binary form is 10, no 3 consecutive set bits are here. S
8 min read
How to swap two bits in a given integer?
Given an integer n and two-bit positions p1 and p2 inside it, swap bits at the given positions. The given positions are from the least significant bit (lsb). For example, the position for lsb is 0.Examples: Input: n = 28, p1 = 0, p2 = 3Output: 21Explanation: 28 in binary is 11100. If we swap 0'th and 3rd digits, we get 10101 which is 21 in decimal.
8 min read
Sort an array according to count of set bits | Set 2
Given an array arr[] of positive integers, the task is to sort the array in decreasing order of count of set bits in binary representations of array elements. For integers having same number of set bits in their binary representation, sort according to their position in the original array i.e., a stable sort. For example, if input array is {3, 5},
6 min read
Sum of numbers obtained by the count of set and non-set bits in diagonal matrix elements
Given a square matrix mat[][] of dimension N*N, convert the elements present in both the diagonals to their respective binary representations and perform the following operations: For every position of bits, count the number of set bits and non-set bits in those binary representations.If count of set bits exceeds that of non-set bits, place 0 at th
10 min read
Minimum decrements to make integer A divisible by integer B
Given two positive integers A and B where A is greater than B. In one move one can decrease A by 1 which implies that after one move A is equal to A - 1. The task is to find the minimum number of moves required to make A divisible by B in constant time. Examples: Input: A = 10, B = 3 Output: 1Explanation: Only one move is required A = A - 1 = 9, wh
3 min read
Cyclic shifts of integer N by another integer m
Given an integer N represented as a binary representation of X = 16 bits. We are also given a number 'm' and a character c which is either L or R. The task is to determine a number M that is generated after cyclically shifting the binary representation of N by m positions either left if c = L or right if c = R.Examples: Input : N = 7881, m = 5, c =
5 min read
Digital Root (repeated digital sum) of square of an integer using Digital root of the given integer
Given an integer N, the task is to find the digital root N2 using the digital root of N. Digital Root of a positive integer is calculated by adding the digits of the integer. If the resultant value is a single digit, then that digit is the digital root. If the resultant value contains two or more digits, those digits are summed and the process is r
6 min read
Minimize operations to convert A to B by adding any odd integer or subtracting any even integer
Given two positive integers A and B. The task is to find the minimum number of operations required to convert number A into B. In a move, any one of the following operations can be applied on the number A: Select any odd integer x (x>0) and add it to A i.e. (A+x);Or, select any even integer y (y>0) and subtract it from A i.e. (A-y). Examples:
5 min read
Check if an integer is rotation of another given integer
Given two integers A and B, the task is to check if the integer A is rotation of the digits of the integer B or not. If found to be true, then print "Yes". Otherwise print "No". Examples: Input: A= 976, B= 679Output: Yes Input: A= 974, B= 2345Output: No Recommended: Please try your approach on {IDE} first, before moving on to the solution.Approach:
9 min read
Count set bits using Python List comprehension
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 = 11 Output : 3 Binary representation of 11 is 1101 and has 3 set bits We have existing solution for this problem please refer Count set bits in an integer link. W
2 min read
Python map function | Count total set bits in all numbers from 1 to n
Given a positive integer n, count the total number of set bits in binary representation of all numbers from 1 to n. Examples: Input: n = 3 Output: 4 Binary representations are 1, 2 and 3 1, 10 and 11 respectively. Total set bits are 1 + 1 + 2 = 4. Input: n = 6 Output: 9 Input: n = 7 Output: 12 Input: n = 8 Output: 13 We have existing solution for t
2 min read
Python | 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 representation of n. Examples: Input : n = 42, l = 2,
2 min read
Count of divisors having more set bits than quotient on dividing N
Given a positive integer N. The task is to find the number of divisors (say d) which gives a quotient (say q) on an integer division (i.e q = N/d) such that the quotient has bits or equal set bits than the divisor. In other words, find the number of the possible values of 'd' which will produce 'q' on an integer dividing 'n' (q = N/d) such that 'q'
9 min read
Range query for count of set bits
Given an array of positive integer and q query which contains two integers, L & R. Task is to find the number of set bits for a given range. Prerequisite : Bitwise Hacks Examples : Input : Arr[] = { 1, 5, 6, 10, 9, 4 } Query : 2 L & R 1 5 2 4 Output : 9 6 Input : Arr[] = { 1, 10, 5, 2, 8, 11, 15 } Query : 2 L & R 2 4 1 5 Output : 4 9 Si
7 min read
Count pairs with set bits sum equal to K
Given an array arr[] and an integer K, the task is to count the pairs whose sum of set bits is KExamples: Input: arr[] = {1, 2, 3, 4, 5}, K = 4 Output: 1 (3, 5) is the only valid pair as the count of set bits in the integers {1, 2, 3, 4, 5} are {1, 1, 2, 1, 2} respectively.Input: arr[] = {5, 42, 35, 22, 7}, K = 6 Output: 6 Naive approach: Initialis
10 min read