Question:
How to count the different bits at same position in binary using C++

Summary

Within the Solution class, we have implemented a function named sumBitDifferences. This function's goal is to figure out the total bit differences between each pair of elements in the provided integer array.


Solution

//User function template for C++

class Solution{

public:

long long sumBitDifferences(int arr[], int n) {

    // code here

    long long ans = 0;

    

    for (int i = 0; i<31; i++) {

        long long ones = 0;

        long long zeroes = 0;

        

        for (int j=0;j<n;j++) 

        {

            if( ((arr[j]>>i)&1)==1)

            ones++;

            else

            zeroes++;

        }

        ans = ans + (ones*zeroes);

    }

    return 2*ans;

}

};


Explanation

  • The function requires two inputs: an integer array called arr and an integer called n, which is the array's size.

  • It sets up a variable called ans to hold the total of the bit differences at the end. The type of this variable is long long to support possibly large amounts.

  • Next, the function uses the outer loop for (int i = 0; i<31; i++) to iterate over each bit position from 0 to 30 (inclusive). 

  • Two variables, ones and zeroes, are initialized inside the outer loop to store the count of elements with the current bit set to 1 or 0, respectively.


Suggested blogs:

>Find the number of pairs of elements whose sum is equal to K using C++

>How to check whether string is palindrome or not using C++

>How to determine the smallest possible size of a vertex cover using C++

>How to reverse the first K elements of queue using C++

>How to find duplicate rows in a binary matrix using C++

>How to find the total number of special sequences possible using C++

>How to Reverse array in groups? C++

>How to represent the maximum value in knapsack using C++


Nisha Patel

Nisha Patel

Submit
0 Answers