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:
- Create a variable cnt to store the answer and initialize it with 0.
- Traverse on each element of the array arr.
- Now for each element, say x, run a loop while it’s greater than 0.
- Extract the last bit of x using (x&1) and then right shift x by a single bit.
- Return cnt as the answer to this problem.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int totalSetBits(vector< int >& arr)
{
int cnt = 0;
for ( auto x : arr) {
while (x > 0) {
cnt += (x & 1);
x >>= 1;
}
}
return cnt;
}
int main()
{
vector< int > arr = { 1, 2, 5, 7 };
cout << totalSetBits(arr);
}
|
Java
import java.util.*;
class GFG{
static int totalSetBits( int [] arr)
{
int cnt = 0 ;
for ( int x : arr) {
while (x > 0 ) {
cnt += (x & 1 );
x >>= 1 ;
}
}
return cnt;
}
public static void main(String[] args)
{
int [] arr = { 1 , 2 , 5 , 7 };
System.out.print(totalSetBits(arr));
}
}
|
Python3
def totalSetBits(arr):
cnt = 0
for x in arr:
while (x > 0 ):
cnt + = (x & 1 )
x >> = 1
return cnt
if __name__ = = "__main__" :
arr = [ 1 , 2 , 5 , 7 ]
print (totalSetBits(arr))
|
C#
using System;
class GFG {
static int totalSetBits( int [] arr)
{
int cnt = 0;
for ( int x = 0; x < arr.Length; x++) {
while (arr[x] > 0) {
cnt += (arr[x] & 1);
arr[x] >>= 1;
}
}
return cnt;
}
public static void Main( string [] args)
{
int [] arr = { 1, 2, 5, 7 };
Console.WriteLine(totalSetBits(arr));
}
}
|
Javascript
<script>
function totalSetBits(arr)
{
let cnt = 0;
for (let x of arr)
{
while (x > 0)
{
cnt += (x & 1);
x >>= 1;
}
}
return cnt;
}
let arr = [ 1, 2, 5, 7 ];
document.write(totalSetBits(arr));
</script>
|
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