Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Count minimum bits to flip such that XOR of A and B equal to C in C++
We are given three binary sequences A, B and C of length N. Each sequence represents a binary number. We have to find the number of bit flips required in A and B such that XOR of A and B results in C.
Syntax
int flipCount(int A[], int B[], int C[], int n);
First, let us understand the XOR operation truth table −
| X | Y | X XOR Y |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
From the XOR truth table, we can derive the following rules for bit flipping −
- If A[i] == B[i] and C[i] == 0, then no flip required
- If A[i] == B[i] and C[i] == 1, then flip either A[i] or B[i] (count = 1)
- If A[i] != B[i] and C[i] == 0, then flip either A[i] or B[i] (count = 1)
- If A[i] != B[i] and C[i] == 1, then no flip required
Example
The following program implements the bit flip counting algorithm −
#include <stdio.h>
int flipCount(int A[], int B[], int C[], int N) {
int count = 0;
for (int i = 0; i < N; ++i) {
// If both A[i] and B[i] are equal then XOR results 0, if C[i] is 1 flip
if (A[i] == B[i] && C[i] == 1)
++count;
// If both A and B are unequal then XOR results 1, if C[i] is 0 flip
else if (A[i] != B[i] && C[i] == 0)
++count;
}
return count;
}
int main() {
// N represents total count of bits
int N = 5;
int a[] = {1, 0, 0, 0, 0};
int b[] = {0, 0, 0, 1, 0};
int c[] = {1, 0, 1, 1, 1};
printf("Minimum bits to flip such that XOR of A and B equal to C: %d\n", flipCount(a, b, c, N));
return 0;
}
Minimum bits to flip such that XOR of A and B equal to C: 2
How It Works
Let's trace through the example step by step −
- i=0: A[0]=1, B[0]=0, C[0]=1. Since A[0] != B[0] and C[0]=1, no flip needed
- i=1: A[1]=0, B[1]=0, C[1]=0. Since A[1] == B[1] and C[1]=0, no flip needed
- i=2: A[2]=0, B[2]=0, C[2]=1. Since A[2] == B[2] and C[2]=1, flip needed (count=1)
- i=3: A[3]=0, B[3]=1, C[3]=1. Since A[3] != B[3] and C[3]=1, no flip needed
- i=4: A[4]=0, B[4]=0, C[4]=1. Since A[4] == B[4] and C[4]=1, flip needed (count=2)
Conclusion
The algorithm checks each bit position and counts flips needed when the current XOR result doesn't match the desired output. The time complexity is O(N) where N is the number of bits.
Advertisements
