Open In App

Count total set bits in an array

Last Updated : 29 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr, the task is to count the total number of set bits in all numbers of that array arr.

Example:

Input: arr[] = {1, 2, 5, 7}
Output: 7
Explanation: Number of set bits in {1, 2, 5, 7} are {1, 1, 2, 3} respectively

Input: arr[] = {0, 4, 9, 8}
Output: 4

 

Approach: Follow the below steps to solve this problem:

  1. Create a variable cnt to store the answer and initialize it with 0.
  2. Traverse on each element of the array arr.
  3. Now for each element, say x, run a loop while it's greater than 0.
  4. Extract the last bit of x using (x&1) and then right shift x by a single bit.
  5. Return cnt as the answer to this problem.

Below is the implementation of the above approach:

C++
// C++ code for the above approach

#include <bits/stdc++.h>
using namespace std;

// Function to count the total number of set bits
// in an array of integers
int totalSetBits(vector<int>& arr)
{
    int cnt = 0;
    for (auto x : arr) {

        // While x is greater than 0
        while (x > 0) {

            // Adding last bit to cnt
            cnt += (x & 1);

            // Right shifting x by a single bit
            x >>= 1;
        }
    }
    return cnt;
}

// Driver Code
int main()
{
    vector<int> arr = { 1, 2, 5, 7 };
    cout << totalSetBits(arr);
}
Java Python C# JavaScript

Output
7

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

Using bin:

  • We use list comprehension to iterate through each element x in the array arr.
  • For each element x, we convert it to a binary string using the built-in bin() function, then count the number of '1's in the binary representation using the count() method.
  • We sum up the counts of set bits for all elements in the array using the sum() function and return the total count.
C++
#include <iostream>
using namespace std;

// Function to count the total number of set bits in an
// array of integers
int totalSetBits(int arr[], int n)
{
    int totalSetBits = 0;
    for (int i = 0; i < n; ++i) {
        totalSetBits += __builtin_popcount(arr[i]);
    }
    return totalSetBits;
}

// Driver Code
int main()
{
    int arr[] = { 1, 2, 5, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << totalSetBits(arr, n) << endl; // Output: 7
    return 0;
}
Java Python JavaScript

Output
7

Time Complexity: O(N⋅M), where N is the number of elements in the array and M is the maximum number of bits in any element.

Space Complexity: O(1)


Next Article
Article Tags :
Practice Tags :

Similar Reads