Open In App
Related Articles

Count total set bits in an array

Improve Article
Improve
Save Article
Save
Like Article
Like

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




// Java code for the above approach
import java.util.*;
 
class GFG{
 
// Function to count the total number of set bits
// in an array of integers
static int totalSetBits(int[] arr)
{
    int cnt = 0;
    for (int 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
public static void main(String[] args)
{
    int[] arr = { 1, 2, 5, 7 };
    System.out.print(totalSetBits(arr));
}
}
 
// This code is contributed by shikhasingrajput


Python3




# python code for the above approach
 
# Function to count the total number of set bits
# in an array of integers
def totalSetBits(arr):
 
    cnt = 0
    for x in 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
if __name__ == "__main__":
 
    arr = [1, 2, 5, 7]
    print(totalSetBits(arr))
 
# This code is contributed by rakeshsahni


C#




// C# code for the above approach
using System;
 
class GFG {
 
    // Function to count the total number of set bits
    // in an array of integers
    static int totalSetBits(int[] arr)
    {
        int cnt = 0;
        for (int x = 0; x < arr.Length; x++) {
 
            // While x is greater than 0
            while (arr[x] > 0) {
 
                // Adding last bit to cnt
                cnt += (arr[x] & 1);
 
                // Right shifting x by a single bit
                arr[x] >>= 1;
            }
        }
        return cnt;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        int[] arr = { 1, 2, 5, 7 };
        Console.WriteLine(totalSetBits(arr));
    }
}
 
// This code is contributed by ukasp.


Javascript




<script>
 
// JavaScript code for the above approach
 
// Function to count the total number of set bits
// in an array of integers
function totalSetBits(arr)
{
    let cnt = 0;
    for(let x of 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
let arr = [ 1, 2, 5, 7 ];
 
document.write(totalSetBits(arr));
 
// This code is contributed by Potta Lokesh
 
</script>


Output

7

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

 


Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Last Updated : 16 Dec, 2021
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials