Add n binary strings | Java program to 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
class GFG { static String addBinaryUtil ( String a , String b ) { String result = " " ; int s = 0 ; int i = a . length ( ) - 1 , j = b . length ( ) - 1 ; while ( i >= 0 j >= 0 s == 1 ) { s += ( ( i >= 0 ) ? a . charAt ( i ) - '0' : 0 ) ; s += ( ( j >= 0 ) ? b . charAt ( j ) - '0' : 0 ) ; result = s % 2 + result ; s /= 2 ; i -- ; j -- ; } return result ; } static String addBinary ( String arr [ ] , int n ) { String result = " " ; for ( int i = 0 ; i < n ; i ++ ) { result = addBinaryUtil ( result , arr [ i ] ) ; } return result ; } public static void main ( String [ ] args ) { String arr [ ] = { "1" , "10" , "11" } ; int n = arr . length ; System . out . println ( addBinary ( arr , n ) ) ; } }