Count set bits in an integer
Last Updated :
15 Feb, 2025
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

[Naive Approach] - One by One Counting
This approach counts the number of set bits (1s) in the binary representation of a given integer. It works by repeatedly checking the least significant bit of the number using the bitwise AND operation (n & 1
). If the least significant bit is 1, the count is incremented. Then, the number is right-shifted by 1 (n >>= 1
), effectively removing the least significant bit and moving on to the next one. This process continues until the number becomes 0, and the function returns the total count of set bits.
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;
}
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));
}
}
Python
# 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))
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));
}
}
JavaScript
// 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;
console.log(countSetBits(i));
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);
?>
Time Complexity: O(log n)
Auxiliary Space: O(1)
Recursive Implementation The function checks if the least significant bit is set (i.e., if it's 1). It does this by using a bitwise operation that isolates the least significant bit. If the bit is 1, it adds 1 to the count; otherwise, it adds 0. After checking the bit, the function recursively calls itself with the number shifted right by one position, essentially removing the checked bit. This process continues until all bits are checked, and the final count of set bits is returned.
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;
}
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;
}
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));
}
}
Python
# 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))
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));
}
}
JavaScript
// 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
console.log (countSetBits(n));
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);
?>
Time Complexity: O(log n)
Auxiliary Space: O(log n)for recursive stack space
[Expected Approach 1] - Brian Kernighan's Algorithm
This approach uses the Brian Kernighan's algorithm to count the number of set bits (1s) in the binary representation of a given integer. The key idea is that the expression n &= (n - 1)
clears the least significant set bit in the number n
. By repeatedly applying this operation, we reduce the number and count how many set bits are cleared, which directly gives us the count of set bits. This method is more efficient than checking each bit individually, as it only processes the set bits in the number, making it faster in cases where the number has fewer set bits.
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.
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.
Python
# 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))
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
JavaScript
// 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;
console.log (countSetBits(i));
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);
?>
Time Complexity: O(log n)
Auxiliary Space: O(1)
[Expected Approach 2] - Using Lookup table
This approach uses a lookup table to count the number of set bits (1s) in a number efficiently.
The program first initializes a table, BitsSetTable256[]
, where each entry at index i
contains the number of set bits in the 8-bit binary representation of i
. This is done by iterating through all numbers from 0 to 255 and calculating the set bits for each.
In the function countSetBits
, the number is divided into 4 bytes (8 bits each), and the lookup table is used to quickly get the number of set bits for each byte. The result is the sum of the set bits in all 4 bytes, giving the total number of set bits in the integer.
This method is fast because it avoids looping through individual bits by using precomputed values stored in the lookup table. It is particularly useful when there are many set bits to count.
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);
}
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))
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));
}
}
JavaScript
// 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;
console.log (countSetBits(n));
Time Complexity: O(1)
Auxiliary Space: O(1)
[Expected Approach 3] - Mapping Nibbles
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;
}
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
Python
# 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
JavaScript
// 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;
console.log (countSetBitsRec(num));
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
?>
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.
Approach: 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;
}
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));
}
}
Python
# 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));
Time Complexity: O(logn)
Auxiliary Space: O(1)
Using Library or Quick Syntax
In C++ GCC, we can directly count set bits using __builtin_popcount(). So we can avoid a separate function for counting set bits. Similarly, we have direct syntax in other programming languages.
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));
}
}
Python
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);
}
}
JavaScript
// Javascript program to demonstrate
// __builtin_popcount()
console.log ((4).toString(2).split('').
filter(x => x == '1').length + "<br>");
console.log ((15).toString(2).split('').
filter(x => x == '1').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";
?>
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem