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
< ? php function addBinaryUtil ( $ a , $ b ) { $ result = " " ; $ s = 0 ; $ i = strlen ( $ a ) - 1 ; $ j = strlen ( $ b ) - 1 ; while ( $ i >= 0 $ j >= 0 $ s == 1 ) { $ s += ( ( $ i >= 0 ) ? ord ( $ a [ $ i ] ) - ord ( '0' ) : 0 ) ; $ s += ( ( $ j >= 0 ) ? ord ( $ b [ $ j ] ) - ord ( '0' ) : 0 ) ; $ result = chr ( $ s % 2 + ord ( '0' ) ) . $ result ; $ s = ( int ) ( $ s / 2 ) ; $ i -- ; $ j -- ; } return $ result ; } function addBinary ( $ arr , $ n ) { $ result = " " ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ result = addBinaryUtil ( $ result , $ arr [ $ i ] ) ; return $ result ; } $ arr = array ( "1" , "10" , "11" ) ; $ n = count ( $ arr ) ; echo addBinary ( $ arr , $ n ) . " STRNEWLINE " ; ? >