Count Set Bits

Last Updated : 19 Jul, 2026

Given a positive integer n. Your task is to return the count of set bits in its binary equivalent.

Examples : 

Input: n = 6
Output: 2
Explanation:

1-

Binary representation is '110', so the count of the set bit is 2.

Input: n = 8
Output: 1
Explanation:

2

Binary representation is '1000', so the count of the set bit is 1.

Input: n = 3
Output: 2
Explanation:

3

Binary representation is '11', so the count of the set bit is 2.

Try It Yourself
redirect icon

[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>
using namespace std;

int setBits(int n)
{
    int cnt = 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;
    }

    return cnt;
}

int main()
{
    int n = 8;

    cout << setBits(n);

    return 0;
}
Java
public class GFG {
    public static int setBits(int n)
    {
        int cnt = 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;
        }

        return cnt;
    }

    public static void main(String[] args)
    {
        int n = 8;

        System.out.println(setBits(n));
    }
}
Python
def setBits(n):
    cnt = 0

    # Traverse all bits of the number.
    while n > 0:

        # If the last bit is set, increment the count.
        if n & 1:
            cnt += 1

        # Move to the next bit.
        n >>= 1

    return cnt


if __name__ == '__main__':
    n = 8

    print(setBits(n))
C#
using System;

public class GFG {
    public static int setBits(int n)
    {
        int cnt = 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;
        }

        return cnt;
    }

    public static void Main()
    {
        int n = 8;

        Console.WriteLine(setBits(n));
    }
}
JavaScript
function setBits(n)
{
    let cnt = 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;
    }

    return cnt;
}

// Driver Code
const n = 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>
using namespace std;

int setBits(int n)
{
    int cnt = 0;

    // Continue until all set bits are removed.
    while (n > 0)
    {

        // Remove the rightmost set bit.
        n = n & (n - 1);

        // Increment the count.
        cnt++;
    }

    return cnt;
}

int main()
{
    int n = 8;

    cout << setBits(n);

    return 0;
}
Java
public class GFG {
    int setBits(int n)
    {
        int cnt = 0;

        // Continue until all set bits are removed.
        while (n > 0) {

            // Remove the rightmost set bit.
            n = n & (n - 1);

            // Increment the count.
            cnt++;
        }

        return cnt;
    }

    public static void main(String[] args)
    {
        GFG obj = new GFG();
        int n = 8;
        System.out.println(obj.setBits(n));
    }
}
Python
def setBits(n):
    cnt = 0

    # Continue until all set bits are removed.
    while n > 0:

        # Remove the rightmost set bit.
        n = n & (n - 1)

        # Increment the count.
        cnt += 1

    return cnt


if __name__ == "__main__":
    n = 8
    print(setBits(n))
C#
using System;

public class GFG {
    public int setBits(int n)
    {
        int cnt = 0;

        // Continue until all set bits are removed.
        while (n > 0) {

            // Remove the rightmost set bit.
            n = n & (n - 1);

            // Increment the count.
            cnt++;
        }

        return cnt;
    }

    public static void Main()
    {
        GFG obj = new GFG();
        int n = 8;
        Console.WriteLine(obj.setBits(n));
    }
}
JavaScript
function setBits(n)
{
    let cnt = 0;

    // Continue until all set bits are removed.
    while (n > 0) {

        // Remove the rightmost set bit.
        n = n & (n - 1);

        // Increment the count.
        cnt++;
    }

    return cnt;
}

// Driver Code
let n = 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>
using namespace std;

int table[256];

// Precompute set bits for all 8-bit numbers.
void initialize()
{
    table[0] = 0;
    for (int i = 1; i < 256; i++)
        table[i] = (i & 1) + table[i / 2];
}

int setBits(int 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];
}

int main()
{
    int n = 8;

    cout << setBits(n);

    return 0;
}
Java
public class GFG {
    static int table[] = new int[256];

    // Precompute set bits for all 8-bit numbers.
    static void initialize()
    {
        table[0] = 0;
        for (int i = 1; i < 256; i++)
            table[i] = (i & 1) + table[i / 2];
    }

    static int setBits(int 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];
    }

    public static void main(String[] args)
    {
        int n = 8;

        System.out.println(setBits(n));
    }
}
Python
# Precompute set bits for all 8-bit numbers.
table = [0] * 256


def initialize():
    table[0] = 0
    for i in range(1, 256):
        table[i] = (i & 1) + table[i // 2]


def setBits(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 = 8
    print(setBits(n))
C#
using System;

public class GFG {
    static int[] table = new int[256];

    // Precompute set bits for all 8-bit numbers.
    static void initialize()
    {
        table[0] = 0;
        for (int i = 1; i < 256; i++)
            table[i] = (i & 1) + table[i / 2];
    }

    static int setBits(int 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];
    }

    public static void Main()
    {
        int n = 8;

        Console.WriteLine(setBits(n));
    }
}
JavaScript
let table = new Array(256).fill(0);

// Precompute set bits for all 8-bit numbers.
function initialize()
{
    table[0] = 0;
    for (let i = 1; i < 256; i++)
        table[i] = (i & 1) + table[Math.floor(i / 2)];
}

function setBits(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];
}

// Driver Code
let n = 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>
using namespace std;

int setBits(int n)
{

    // Lookup table for all possible 4-bit values.
    int table[16] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};

    int cnt = 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;
    }

    return cnt;
}

int main()
{
    int n = 8;

    cout << setBits(n);

    return 0;
}
Java
public class GFG {

    // Lookup table for all possible 4-bit values.
    private static final int[] table = { 0, 1, 1, 2, 1, 2,
                                         2, 3, 1, 2, 2, 3,
                                         2, 3, 3, 4 };

    public static int setBits(int n)
    {

        int cnt = 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;
        }

        return cnt;
    }

    public static void main(String[] args)
    {
        int n = 8;
        System.out.println(setBits(n));
    }
}
Python
def setBits(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.
    while n > 0:

        # Add the set bits in the last nibble.
        cnt += table[n & 15]

        # Remove the processed nibble.
        n >>= 4

    return cnt


if __name__ == '__main__':
    n = 8
    print(setBits(n))
C#
using System;

class GFG {

    // Lookup table for all possible 4-bit values.
    private static readonly int[] table = {
        0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4
    };

    public static int setBits(int n)
    {

        int cnt = 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;
        }

        return cnt;
    }

    static void Main()
    {
        int n = 8;
        Console.WriteLine(setBits(n));
    }
}
JavaScript
function setBits(n)
{

    // Lookup table for all possible 4-bit values.
    const table =
        [ 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 ];

    let cnt = 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;
    }

    return cnt;
}

// Driver Code
const n = 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>
using namespace std;

int setBits(int n)
{

    // Returns the number of set bits.
    return __builtin_popcount(n);
}

int main()
{
    int n = 8;

    cout << setBits(n);

    return 0;
}
Java
class GFG {
    public static int setBits(int n)
    {

        // Returns the number of set bits.
        return Integer.bitCount(n);
    }

    public static void main(String[] args)
    {
        int n = 8;

        System.out.println(setBits(n));
    }
}
Python
def setBits(n):
    # Returns the number of set bits.
    return bin(n).count('1')


if __name__ == '__main__':
    n = 8
    print(setBits(n))
C#
using System;
using System.Numerics;

class GFG {
    public static int SetBits(int n)
    {
        // Returns the number of set bits.
        return BitOperations.PopCount((uint)n);
    }

    static void Main()
    {
        int n = 8;

        Console.WriteLine(SetBits(n));
    }
}
JavaScript
function setBits(n)
{
    // Returns the number of set bits.
    return n.toString(2).split("0").join("").length;
}

// Driver Code
let n = 8;
console.log(setBits(n));

Output
1
Comment