From cf5a12ab877a37a2aba917a88e0cf2801e7a9eb6 Mon Sep 17 00:00:00 2001 From: Menochio <94154713+Menochio@users.noreply.github.com> Date: Thu, 27 Oct 2022 22:01:37 +0530 Subject: [PATCH] Create Bit Difference --- Bit Difference | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Bit Difference diff --git a/Bit Difference b/Bit Difference new file mode 100644 index 0000000..e150b22 --- /dev/null +++ b/Bit Difference @@ -0,0 +1,47 @@ +// C++ program to compute sum of pairwise bit differences +#include +using namespace std; + +int sum_bit_diff(vector a) +{ + int n = a.size(); + int ans = 0; + + for (int i = 0; i < n - 1; i++) { + int count = 0; + + for (int j = i; j < n; j++) { + // Bitwise and of pair (a[i], a[j]) + int x = a[i] & a[j]; + // Bitwise or of pair (a[i], a[j]) + int y = a[i] | a[j]; + + bitset<32> b1(x); + bitset<32> b2(y); + + // to count set bits in and of two numbers + int r1 = b1.count(); + // to count set bits in or of two numbers + int r2 = b2.count(); + + // Absolute differences at individual bit positions of two + // numbers is contributed by pair (a[i], a[j]) in count + count = abs(r1 - r2); + + // each pair adds twice of contributed count + // as both (a, b) and (b, a) are considered + // two separate pairs. + ans = ans + (2 * count); + } + } + return ans; +} + +int main() +{ + + vector nums{ 10, 5 }; + int ans = sum_bit_diff(nums); + + cout << ans; +}