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 <bits/stdc++.h>
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
<script>
// Javascript implementation of the approach
// Function to insert n 0s in the
// beginning of the given string
function addZeros(str, n)
{
for (let i = 0; i < n; i++)
{
str = "0" + str;
}
return str;
}
// Function to return the XOR
// of the given strings
function getXOR(a, b)
{
// Lengths of the given strings
let aLen = a.length;
let 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
let len = Math.max(aLen, bLen);
// To store the resultant XOR
let res = "";
for (let i = 0; i < len; i++)
{
if (a[i] == b[i])
res += "0";
else
res += "1";
}
return res;
}
let a = "11001", b = "111111";
document.write(getXOR(a, b));
// This code is contributed by divyeshrabadiya07.
</script>
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 <bits/stdc++.h>
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
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.
Similar Reads
XOR of two Binary Strings
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
7 min read
XOR of all substrings of a given Binary String
Given a binary string str of size N, the task is to calculate the bitwise XOR of all substrings of str. Examples: Input: str = "11"Output: 11Explanation: The substrings of "11" are: 1, 1, and 11.Their XOR = 1 â 1 â 11 = 11 Input: str = "110"Output: 111Explanation: The substrings of 110 are: 1, 1, 0,
6 min read
What is Binary String?
A binary string is a string that only has two characters, usually the numbers 0 and 1, and it represents a series of binary digits. Binary String Variables:In computer programming, binary string variables are used to store binary data, which is data that is represented in a binary (base-2) format, r
9 min read
Add two binary strings
Given two binary strings s1 and s2, the task is to return their sum.The input strings may contain leading zeros but the output string should not have any leading zeros.Example: Input: s1 = "1101", s2 = "111" Output: "10100" Explanation:Input: s1 = "00100", s2 = "010" Output: "110" Bit-by-bit additio
8 min read
Count of binary string of length N with X 0s and Y 1s
Given positive integers N, X and Y. The task is to find the count of unique binary strings of length N having X 0s and Y 1s. Examples: Input: N=5, X=3, Y=2Output: 10Explanation: There are 10 binary strings of length 5 with 3 0s and 2 1s, such as: 00011, 00101, 01001, 10001, 00110, 01010, 10010, 0110
4 min read
Count of distinct XORs formed by rearranging two Binary strings
Given two binary strings A and B of equal length N, the task is to find the number of distinct XORs possible by arbitrarily reordering the two binary strings. Since the number can be large enough, find the number modulo 109 + 7 Examples: Input: A = "00", B = "01" Output: 2 Explanation: There are two
15 min read
Bitwise AND of N binary strings
Given an array arr[] of binary strings, the task is to calculate the bitwise AND of all of these strings and print the resultant string. Examples: Input: arr[] = {"101", "110110", "111"}Output: 000100Explanation: (000101) & (110110) & (000111) = 000100 Input: arr[] = {"110010101", "111101001
15+ min read
Find uncommon characters of the two strings
Given two strings s1 and s2, the task is to find the uncommon characters in both strings. An uncommon character means that the character is present in only one string or in another string but not in both. The strings contain only lowercase characters and can have duplicates. Note: Output the uncommo
12 min read
Minimum number of swaps to make two binary string equal
Given two binary strings of equal length, the task is to find the minimum number of swaps to make them equal. Swapping between two characters from two different strings is only allowed, return -1 if strings can't be made equal. Examples: Input: s1 = "0011", s2 = "1111" Output: 1Explanation:Swap s1[0
12 min read
Print all interleavings of given two strings
Given two strings str1 and str2, write a function that prints all interleavings of the given two strings. You may assume that all characters in both strings are different Example: Input: str1 = "AB", str2 = "CD"Output: ABCD ACBD ACDB CABD CADB CDABInput: str1 = "AB", str2 = "C"Output: ABC ACB CABAn
14 min read