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 program
function addBinaryUtil ( a , b ) { var result = " " ; var s = 0 ; var i = a . length - 1 , j = b . length - 1 ; while ( i >= 0 j >= 0 s == 1 ) { s += ( ( i >= 0 ) ? a . charCodeAt ( i ) - ' ' . charCodeAt ( 0 ) : 0 ) ; s += ( ( j >= 0 ) ? b . charCodeAt ( j ) - ' ' . charCodeAt ( 0 ) : 0 ) ; result = String . fromCharCode ( ( s % 2 == 1 ? 1 : 0 ) + ' ' . charCodeAt ( 0 ) ) + result ; s = parseInt ( s / 2 ) ; i -- ; j -- ; } return result ; } function addBinary ( arr , n ) { var result = " " ; for ( var i = 0 ; i < n ; i ++ ) result = addBinaryUtil ( result , arr [ i ] ) ; return result ; } var arr = [ " " , " " , " " ] ; var n = arr . length ; document . write ( addBinary ( arr , n ) ) ;