int a[] = {3,3,3,5,2,2,2};
for(int i =0 ; i < 32 ; i++)
{
int count = 0;
for(int j = 0 ; j < a.length ; j++)
{
if((a[j] & (1<<i)) == 1)
count++;
}
}

The above code doesn’t give the correct output.

1 Like

int totalsetbits=0;
for(int i =0 ; i <a.length ; i++)
{
int count = 0;
for(int j = 0 ; j < 32 ; j++)
{
if((a[i] & (1<<j)) >0)
totalsetbits++; // total set bit for every every element of the array
}
}

1 Like

Can you please explain what difference the position of the two loops make in your solution and mine?

see integer value has atmost 32 bits in binaryform .
so what we are doing is for every element of array a[i] we are interating at all 32 bit of a[i] and checking which is set by a[i]&(1<<j)>0.

suppose a[i] is 3 then in binary it can be written as 000…11 total length is 32 and we are interating this 32 bits and checking a[i]&(1<<j) (left shifting bit 1 by j) is greater than zero . answer will be 2 as 3 has set bit at 0 and 1 position.

Hope you got it now.

1 Like

The focus should not be on reordering of loops , as it will work fine with your order of loops also.
But the condition for checking set bit should be if((a[j] & (1<<i)) > 0) as then it would give the desired output that the current bit is set or not, because if the bit is set then the bitwise & can be any number greater than 0 depending on bit to be checked and the input number.

1 Like

Yeah also he have count function inside the loop that should be outside

Yes thank you so much.

This was very helpful. Thank you so very much. I understood the small mistake I was not paying attention to. Thanks.

A more easy way would be to use __builtin_popcount(). In GCC, we can directly count set bits for a number using this.