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