Saturday, 23 Oct 2021

# Product of count of set bits present in binary representations of elements in an array

Product of count of set bits present in binary representations of elements in an arrayGiven an array arr[] consisting of N integers, the task is to find the product of the count of set bits in the binary representation of every array element.Examples:Input: arr[] = {3, 2, 4, 1, 5}Output: 4Explanation:Binary representation of the array elements are {3, 2, 4, 1, 5} are {“11”, “10”, “100”, “1”, “101”} respectively.Therefore, the product of count of set bits = (2 * 1 * 1 * 1 * 2) = 4.Input: arr[] = {10, 11, 12}Output: 12Approach: The given problem can be solved by counting the total bits in the binary representation of every array element. Follow the steps below to solve the problem:Initialize a variable, say product, to store the resultant product.Traverse the given array arr[] and perform the following steps:After completing the above steps, print the value of the product as the result.Below is the implementation of the above approach:C++  #include using namespace std;  int countbits(int n){        int count = 0;          while (n != 0) {                  if (n & 1)            count++;                  n = n / 2;    }          return count;}  int BitProduct(int arr[], int N){        int product = 1;          for (int i = 0; i < N; i++) {                          int bits = countbits(arr[i]);                  product *= bits;    }          return product;}  int main(){    int arr[] = { 3, 2, 4, 1, 5 };    int N = sizeof(arr) / sizeof(arr);    cout