Add n binary strings | This function adds two binary strings and return result as a third string ; Initialize result ; Initialize digit sum ; Traverse both strings starting from last characters ; Compute sum of last digits and carry ; If current digit sum is 1 or 3 , add 1 to result ; Compute carry ; Move to next digits ; function to add n binary strings ; Driver code
def addBinaryUtil ( a , b ) : NEW_LINE result = " " ; NEW_LINE s = 0 ; NEW_LINE INDENT i = len ( a ) - 1 ; NEW_LINE j = len ( b ) - 1 ; NEW_LINE while ( i >= 0 or j >= 0 or s == 1 ) : NEW_LINE INDENT s += ( ord ( a [ i ] ) - ord ( '0' ) ) if ( i >= 0 ) else 0 ; NEW_LINE s += ( ord ( b [ j ] ) - ord ( '0' ) ) if ( j >= 0 ) else 0 ; NEW_LINE result = chr ( s % 2 + ord ( '0' ) ) + result ; NEW_LINE s //= 2 ; NEW_LINE i -= 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT def addBinary ( arr , n ) : NEW_LINE INDENT result = " " ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT result = addBinaryUtil ( result , arr [ i ] ) ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT arr = [ "1" , "10" , "11" ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( addBinary ( arr , n ) ) ; NEW_LINE