Open In App

XOR of two Binary Strings

Improve
Improve
Like Article
Like
Save
Share
Report

Given two binary strings A and B of equal lengths, the task is to print a string that is the XOR of Binary Strings A and B.

Examples: 

Input: A = “0001”, B = “0010” 
Output: 0011

Input: A = “1010”, B = “0101” 
Output: 1111 

Approach: The idea is to iterate over both the string character by character and if the character is mismatched then add “1” as the character in the answer string otherwise add “0” to the answer string to generate the XOR string.

Below is the implementation of the above approach:

C++




// C++ Implementation to find the
// XOR of the two Binary Strings
#include<bits/stdc++.h>
using namespace std;
 
// Function to find the
// XOR of the two Binary Strings
string xoring(string a, string b, int n){
string ans = "";
     
    // Loop to iterate over the
    // Binary Strings
    for (int i = 0; i < n; i++)
    {
        // If the Character matches
        if (a[i] == b[i])
            ans += "0";
        else
            ans += "1";
    }
    return ans;
}
 
// Driver Code
int main()
{
    string a = "1010";
    string b = "1101";
    int n = a.length();
    string c = xoring(a, b, n);
    cout << c << endl;
}
 
// This code is contributed by Surendra_Gangwar


Java




// Java Implementation to find the
// XOR of the two Binary Strings
import java.io.*;
 
class GFG {
    // Function to find the
    // XOR of the two Binary Strings
    static String  xoring(String a, String b, int n){
    String ans = "";
         
        // Loop to iterate over the
        // Binary Strings
        for (int i = 0; i < n; i++)
        {
            // If the Character matches
            if (a.charAt(i) == b.charAt(i))
                ans += "0";
            else
                ans += "1";
        }
        return ans;
    }
     
    // Driver Code
    public static void main (String[] args)
    {
        String a = "1010";
        String b = "1101";
        int n = a.length();
        String c = xoring(a, b, n);
        System.out.println(c);
    }
}
 
// This code is contributed by shubhamsingh10


Python3




# Python Implementation to find the
# XOR of the two Binary Strings
 
# Function to find the
# XOR of the two Binary Strings
def xor(a, b, n):
    ans = ""
     
    # Loop to iterate over the
    # Binary Strings
    for i in range(n):
         
        # If the Character matches
        if (a[i] == b[i]):
            ans += "0"
        else:
            ans += "1"
    return ans
 
# Driver Code
if __name__ == "__main__":
    a = "1010"
    b = "1101"
    n = len(a)
    c = xor(a, b, n)
    print(c)


C#




// C# Implementation to find the
// XOR of the two Binary Strings
using System;
 
class GFG{
    // Function to find the
    // XOR of the two Binary Strings
    static string xoring(string a, string b, int n){
    string ans = "";
         
        // Loop to iterate over the
        // Binary Strings
        for (int i = 0; i < n; i++)
        {
            // If the Character matches
            if (a[i] == b[i])
                ans += "0";
            else
                ans += "1";
        }
        return ans;
    }
     
    // Driver Code
    static public void Main ()
    {
        string a = "1010";
        string b = "1101";
        int n = a.Length;
        string c = xoring(a, b, n);
        Console.WriteLine(c);
    }
}
 
// This code is contributed by shubhamsingh10


Javascript




<script>
 
// Javascript Implementation to find the
// XOR of the two Binary Strings
 
// Function to find the
// XOR of the two Binary Strings
function xoring(a, b, n){
let ans = "";
     
    // Loop to iterate over the
    // Binary Strings
    for (let i = 0; i < n; i++)
    {
        // If the Character matches
        if (a[i] == b[i])
            ans += "0";
        else
            ans += "1";
    }
    return ans;
}
 
// Driver Code
    let a = "1010";
    let b = "1101";
    let n = a.length;
    let c = xoring(a, b, n);
    document.write(c);
 
</script>


Output

0111








Time Complexity: O(N)
Auxiliary Space: O(N)

method2:performs XOR operation bit by bit to generate the XOR result string.

Approach: We take  two binary strings A and B as input which  are of equal length, and apply for loop and performs XOR operation bit by bit to generate the XOR result. Then we print the XOR result string.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to perform XOR of two binary strings
std::string xor_Binary_Strings( string &A,string &B) {
   int len = A.length(); // Get the length of binary strings A and B
   string result = ""; // Initialize the result string
 
   // Perform XOR operation bit by bit
   for (int i = 0; i < len; i++) {
       // XOR of current bits and convert it to char ('0' or '1')
       char currentXOR = ((A[i] - '0') ^ (B[i] - '0')) + '0';
       // Append the currentXOR to the result string
       result += currentXOR;
   }
 
   return result;
}
 
int main() {
   // Input two binary strings of equal length
   string A= "1010";
   string B = "1101";
   int n = A.length();
   string C =xor_Binary_Strings(A,B);
   cout << C << endl;
   return 0;
}


Java




public class Main {
    // Function to perform XOR of two binary strings
    public static String xorBinaryStrings(String A,
                                          String B)
    {
        int len = A.length(); // Get the length of binary
                              // strings A and B
        StringBuilder result
            = new StringBuilder(); // Initialize the result
                                   // StringBuilder
 
        // Perform XOR operation bit by bit
        for (int i = 0; i < len; i++) {
            // XOR of current bits and convert it to char
            // ('0' or '1')
            char currentXOR
                = (char)((A.charAt(i) - '0')
                         ^ (B.charAt(i) - '0') + '0');
            // Append the currentXOR to the result
            // StringBuilder
            result.append(currentXOR);
        }
 
        return result.toString();
    }
 
    public static void main(String[] args)
    {
        // Input two binary strings of equal length
        String A = "1010";
        String B = "1101";
        int n = A.length();
        String C = xorBinaryStrings(A, B);
        System.out.println(C);
    }
}
// This code is contributed by Samim Hossain Mondal.


Python




# Function to perform XOR of two binary strings
def xor_binary_strings(A, B):
    length = len(A)  # Get the length of binary strings A and B
    result = ""  # Initialize the result string
 
    # Perform XOR operation bit by bit
    for i in range(length):
        # XOR of current bits and convert it to a character ('0' or '1')
        current_xor = str(int(A[i]) ^ int(B[i]))
        # Append the current_xor to the result string
        result += current_xor
 
    return result
 
 
def main():
    # Input two binary strings of equal length
    A = "1010"
    B = "1101"
    C = xor_binary_strings(A, B)
    print(C)
 
 
if __name__ == "__main__":
    main()


C#




using System;
 
class Program {
    // Function to perform XOR of two binary strings
    static string XorBinaryStrings(string A, string B)
    {
        int len = A.Length; // Get the length of binary
                            // strings A and B
        string result = ""; // Initialize the result string
 
        // Perform XOR operation bit by bit
        for (int i = 0; i < len; i++) {
            // XOR of current bits and convert it to char
            // ('0' or '1')
            char currentXOR
                = (char)((A[i] - '0') ^ (B[i] - '0') + '0');
            // Append the currentXOR to the result string
            result += currentXOR;
        }
 
        return result;
    }
 
    static void Main(string[] args)
    {
        // Input two binary strings of equal length
        string A = "1010";
        string B = "1101";
        int n = A.Length;
        string C = XorBinaryStrings(A, B);
        Console.WriteLine(C);
    }
}


Javascript




// Function to perform XOR of two binary strings
function xorBinaryStrings(A, B) {
    const len = A.length; // Get the length of binary strings A and B
    let result = ''; // Initialize the result string
 
    // Perform XOR operation bit by bit
    for (let i = 0; i < len; i++) {
        // XOR of current bits and convert it to '0' or '1'
        const currentXOR = String(Number(A[i]) ^ Number(B[i]));
        // Append the currentXOR to the result string
        result += currentXOR;
    }
 
    return result;
}
 
// Main function
function main() {
    // Input two binary strings of equal length
    const A = '1010';
    const B = '1101';
    const C = xorBinaryStrings(A, B);
    console.log(C);
}
 
// Call the main function
main();


Output

0111



Time Complexity: O(N)
Auxiliary Space: O(N)



Last Updated : 03 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads