# XOR two binary strings of unequal lengths

Last Updated : 29 Oct, 2023

Given two binary string of unequal lengths A and B, the task is to print the binary string which is the XOR of A and B.
Examples:

Input: A = “11001”, B = “111111”
Output: 100110
Input: A = “11111”, B = “0”
Output: 11111

Approach: The idea is to first make both the strings of equal length and then perform the XOR of each character one by one and store it in the resultant string.
Below is the implementation of the above approach:

## C++

 `// C++ implementation of the approach` `#include ` `using` `namespace` `std;`   `// Function to insert n 0s in the` `// beginning of the given string` `void` `addZeros(string& str, ``int` `n)` `{` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``str = ``"0"` `+ str;` `    ``}` `}`   `// Function to return the XOR` `// of the given strings` `string getXOR(string a, string b)` `{`   `    ``// Lengths of the given strings` `    ``int` `aLen = a.length();` `    ``int` `bLen = b.length();`   `    ``// Make both the strings of equal lengths` `    ``// by inserting 0s in the beginning` `    ``if` `(aLen > bLen) {` `        ``addZeros(b, aLen - bLen);` `    ``}` `    ``else` `if` `(bLen > aLen) {` `        ``addZeros(a, bLen - aLen);` `    ``}`   `    ``// Updated length` `    ``int` `len = max(aLen, bLen);`   `    ``// To store the resultant XOR` `    ``string res = ``""``;` `    ``for` `(``int` `i = 0; i < len; i++) {` `        ``if` `(a[i] == b[i])` `            ``res += ``"0"``;` `        ``else` `            ``res += ``"1"``;` `    ``}`   `    ``return` `res;` `}`   `// Driver code` `int` `main()` `{` `    ``string a = ``"11001"``, b = ``"111111"``;`   `    ``cout << getXOR(a, b);`   `    ``return` `0;` `}`

## Java

 `// Java implementation of the approach ` `class` `GFG ` `{` `    `  `    ``// Function to insert n 0s in the ` `    ``// beginning of the given string ` `    ``static` `String addZeros(String str, ``int` `n) ` `    ``{ ` `        ``for` `(``int` `i = ``0``; i < n; i++) ` `        ``{ ` `            ``str = ``"0"` `+ str; ` `        ``} ` `        ``return` `str;` `    ``} ` `    `  `    ``// Function to return the XOR ` `    ``// of the given strings ` `    ``static` `String getXOR(String a, String b) ` `    ``{ ` `    `  `        ``// Lengths of the given strings ` `        ``int` `aLen = a.length(); ` `        ``int` `bLen = b.length(); ` `    `  `        ``// Make both the strings of equal lengths ` `        ``// by inserting 0s in the beginning ` `        ``if` `(aLen > bLen) ` `        ``{ ` `            ``a = addZeros(b, aLen - bLen); ` `        ``} ` `        ``else` `if` `(bLen > aLen) ` `        ``{ ` `            ``a = addZeros(a, bLen - aLen); ` `        ``} ` `    `  `        ``// Updated length ` `        ``int` `len = Math.max(aLen, bLen); ` `    `  `        ``// To store the resultant XOR ` `        ``String res = ``""``; ` `        `  `        ``for` `(``int` `i = ``0``; i < len; i++)` `        ``{ ` `            ``if` `(a.charAt(i) == b.charAt(i)) ` `                ``res += ``"0"``; ` `            ``else` `                ``res += ``"1"``; ` `        ``} ` `        ``return` `res; ` `    ``} ` `    `  `    ``// Driver code ` `    ``public` `static` `void` `main (String[] args)` `    ``{ ` `        ``String a = ``"11001"``, b = ``"111111"``; ` `    `  `        ``System.out.println(getXOR(a, b)); ` `    ``} ` `}`   `// This code is contributed by AnkitRai01`

## Python3

 `# Python3 implementation of the approach`   `# Function to insert n 0s in the` `# beginning of the given string` `def` `addZeros(strr, n):` `    ``for` `i ``in` `range``(n):` `        ``strr ``=` `"0"` `+` `strr` `    ``return` `strr`   `# Function to return the XOR` `# of the given strings` `def` `getXOR(a, b):`   `    ``# Lengths of the given strings` `    ``aLen ``=` `len``(a)` `    ``bLen ``=` `len``(b)`   `    ``# Make both the strings of equal lengths` `    ``# by inserting 0s in the beginning` `    ``if` `(aLen > bLen):` `        ``b ``=` `addZeros(b, aLen ``-` `bLen)` `    ``elif` `(bLen > aLen):` `        ``a ``=` `addZeros(a, bLen ``-` `aLen)`   `    ``# Updated length` `    ``lenn ``=` `max``(aLen, bLen)`   `    ``# To store the resultant XOR` `    ``res ``=` `""` `    ``for` `i ``in` `range``(lenn):` `        ``if` `(a[i] ``=``=` `b[i]):` `            ``res ``+``=` `"0"` `        ``else``:` `            ``res ``+``=` `"1"`   `    ``return` `res`   `# Driver code` `a ``=` `"11001"` `b ``=` `"111111"`   `print``(getXOR(a, b))`   `# This code is contributed by Mohit Kumar`

## C#

 `// C# implementation of the approach ` `using` `System;`   `class` `GFG ` `{` `    `  `    ``// Function to insert n 0s in the ` `    ``// beginning of the given string ` `    ``static` `String addZeros(String str, ``int` `n) ` `    ``{ ` `        ``for` `(``int` `i = 0; i < n; i++) ` `        ``{ ` `            ``str = ``"0"` `+ str; ` `        ``} ` `        ``return` `str;` `    ``} ` `    `  `    ``// Function to return the XOR ` `    ``// of the given strings ` `    ``static` `String getXOR(String a, String b) ` `    ``{ ` `    `  `        ``// Lengths of the given strings ` `        ``int` `aLen = a.Length; ` `        ``int` `bLen = b.Length; ` `    `  `        ``// Make both the strings of equal lengths ` `        ``// by inserting 0s in the beginning ` `        ``if` `(aLen > bLen) ` `        ``{ ` `            ``a = addZeros(b, aLen - bLen); ` `        ``} ` `        ``else` `if` `(bLen > aLen) ` `        ``{ ` `            ``a = addZeros(a, bLen - aLen); ` `        ``} ` `    `  `        ``// Updated length ` `        ``int` `len = Math.Max(aLen, bLen); ` `    `  `        ``// To store the resultant XOR ` `        ``String res = ``""``; ` `        `  `        ``for` `(``int` `i = 0; i < len; i++)` `        ``{ ` `            ``if` `(a[i] == b[i]) ` `                ``res += ``"0"``; ` `            ``else` `                ``res += ``"1"``; ` `        ``} ` `        ``return` `res; ` `    ``} ` `    `  `    ``// Driver code ` `    ``public` `static` `void` `Main(String[] args)` `    ``{ ` `        ``String a = ``"11001"``, b = ``"111111"``; ` `    `  `        ``Console.WriteLine(getXOR(a, b)); ` `    ``} ` `}`   `// This code is contributed by Rajput-Ji`

## Javascript

 ``

Output

```100110

```

Time Complexity: O(len), len=Max(length a,length b)
Auxiliary Space: O(len)

Approach:

In this approach, we first determine the length of the larger string and iterate over it. For each index, we extract the corresponding bits from both input strings and perform a bitwise XOR operation on them. We then append the result to the output string. Finally, we return the output string.

Note that we use the expression (i < n) ? a[n – i – 1] – ‘0’ : 0 to extract the bit at index i from the string a. This is because the bits in a are stored in reverse order compared to their position in the binary number. So we need to access the bits in reverse order by subtracting i from the length of the string and subtracting 1 (since the index starts from 0). We also subtract ‘0’ from the bit to convert it from a character to an integer. Similarly, we extract the corresponding bit from b and perform the XOR operation.

Below is the implementation of the above approach:

## C++

 `// C++ implementation of the approach` `#include ` `using` `namespace` `std;`     `// Function to return the XOR` `// of the given strings` `string getXOR(string a, string b)` `{` `    ``string result = ``""``;` `    ``int` `n = a.length();` `    ``int` `m = b.length();` `    ``int` `len = max(n, m);` `    `  `    ``for``(``int` `i = 0; i < len; i++) {` `        ``int` `x = (i < n) ? a[n - i - 1] - ``'0'` `: 0;` `        ``int` `y = (i < m) ? b[m - i - 1] - ``'0'` `: 0;` `        ``int` `z = x ^ y;` `        ``result = (``char``)(z + ``'0'``) + result;` `    ``}` `    `  `    ``return` `result;` `}`     `// Driver code` `int` `main()` `{` `    ``string a = ``"11001"``, b = ``"111111"``;`   `    ``cout << getXOR(a, b);`   `    ``return` `0;` `}`

## Java

 `public` `class` `GFG {` `    ``// Function to return the XOR of two binary strings` `    ``public` `static` `String getXOR(String a, String b) {` `        ``String result = ``""``;` `        ``int` `n = a.length();` `        ``int` `m = b.length();` `        ``int` `len = Math.max(n, m);`   `        ``for` `(``int` `i = ``0``; i < len; i++) {` `            ``int` `x = (i < n) ? a.charAt(n - i - ``1``) - ``'0'` `: ``0``;` `            ``int` `y = (i < m) ? b.charAt(m - i - ``1``) - ``'0'` `: ``0``;` `            ``int` `z = x ^ y;` `            ``result = (``char``) (z + ``'0'``) + result;` `        ``}`   `        ``return` `result;` `    ``}`   `    ``public` `static` `void` `main(String[] args) {` `        ``String a = ``"11001"``;` `        ``String b = ``"111111"``;`   `        ``System.out.println(getXOR(a, b));` `    ``}` `}`

## Python3

 `# Function to return the XOR of the given binary strings` `def` `get_xor(a, b):` `    ``result ``=` `""                 ``# Initialize an empty string to store the XOR result` `    ``n ``=` `len``(a)                  ` `    ``m ``=` `len``(b)                 ` `    ``length ``=` `max``(n, m)         ` `    `  `    ``for` `i ``in` `range``(length):     ``# Iterate through each bit position` `        ``x ``=` `int``(a[n ``-` `i ``-` `1``]) ``if` `i < n ``else` `0`   `# Get i-th bit of 'a' or 0 if it doesn't exist` `        ``y ``=` `int``(b[m ``-` `i ``-` `1``]) ``if` `i < m ``else` `0`   `# Get i-th bit of 'b' or 0 if it doesn't exist` `        ``z ``=` `x ^ y               ``# Calculate XOR of x and y` `        ``result ``=` `str``(z) ``+` `result               ``# Prepend the XOR result to the 'result' string` `    `  `    ``return` `result` `# Driver code` `def` `main():` `    ``a ``=` `"11001"` `    ``b ``=` `"111111"`   `    ``print``(get_xor(a, b))       ``# Print the XOR of 'a' and 'b'`   `if` `__name__ ``=``=` `"__main__"``:` `    ``main()`

## C#

 `using` `System;`   `class` `GFG {` `    ``// Function to return the XOR of the given binary` `    ``// strings` `    ``static` `string` `GetXOR(``string` `a, ``string` `b)` `    ``{` `        ``string` `result = ``""``; ``// Initialize an empty string to` `                            ``// store the XOR result` `        ``int` `n = a.Length; ``// Get the length of string 'a'` `        ``int` `m = b.Length; ``// Get the length of string 'b'` `        ``int` `len = Math.Max(n, m); ``// Find the maximum length` `                                  ``// between 'a' and 'b'`   `        ``for` `(``int` `i = 0; i < len; i++) {` `            ``// Extract the binary digits (0 or 1) from the` `            ``// right side of 'a' and 'b'` `            ``int` `x = (i < n) ? a[n - i - 1] - ``'0'` `: 0;` `            ``int` `y = (i < m) ? b[m - i - 1] - ``'0'` `: 0;`   `            ``// Calculate the XOR of corresponding digits` `            ``int` `z = x ^ y;`   `            ``// Convert the XOR result back to a character` `            ``// ('0' or '1') and prepend it to the result` `            ``// string` `            ``result = (``char``)(z + ``'0'``) + result;` `        ``}`   `        ``return` `result; ``// Return the final XOR result as a` `                       ``// binary string` `    ``}`   `    ``// Driver code` `    ``static` `void` `Main()` `    ``{` `        ``string` `a = ``"11001"``; ``// First binary string` `        ``string` `b = ``"111111"``; ``// Second binary string`   `        ``// Call the XOR function and print the result` `        ``Console.WriteLine(GetXOR(a, b));` `    ``}` `}`

## Javascript

 `// Function to return the XOR of the given strings` `function` `getXOR(a, b) {` `    ``let result = ``""``;` `    ``const n = a.length;` `    ``const m = b.length;` `    ``const len = Math.max(n, m);`   `    ``for` `(let i = 0; i < len; i++) {` `        ``const x = i < n ? parseInt(a[n - i - 1]) : 0; ``// Get the current bit from string ` `                                                      ``// 'a' (right to left)` `        ``const y = i < m ? parseInt(b[m - i - 1]) : 0; ``// Get the current bit from string 'b' ` `                                                      ``// (right to left)` `        ``const z = x ^ y; ``// XOR operation between the two bits` `        ``result = z.toString() + result; ``// Add the result bit to the final string` `    ``}`   `    ``return` `result;` `}`   `// Driver code` `const a = ``"11001"``;` `const b = ``"111111"``;`   `console.log(getXOR(a, b)); ``// Output the XOR result`

Output

```100110

```

Time Complexity: O(max(n, m)), where n and m are the lengths of the input strings A and B, respectively.
Space Complexity: O(max(n, m)), as we need to create a new string to store the XOR of the input strings.