XOR two binary strings of unequal lengths | Java 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
class GFG { static String addZeros ( String str , int n ) { for ( int i = 0 ; i < n ; i ++ ) { str = "0" + str ; } return str ; } static String getXOR ( String a , String b ) { int aLen = a . length ( ) ; int bLen = b . length ( ) ; if ( aLen > bLen ) { a = addZeros ( b , aLen - bLen ) ; } else if ( bLen > aLen ) { a = addZeros ( a , bLen - aLen ) ; } int len = Math . max ( aLen , bLen ) ; String res = " " ; for ( int i = 0 ; i < len ; i ++ ) { if ( a . charAt ( i ) == b . charAt ( i ) ) res += "0" ; else res += "1" ; } return res ; } public static void main ( String [ ] args ) { String a = "11001" , b = "111111" ; System . out . println ( getXOR ( a , b ) ) ; } }