Add n binary strings | C ++ 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 program
#include <bits/stdc++.h> NEW_LINE using namespace std ; string addBinaryUtil ( string a , string b ) { string result = " " ; int s = 0 ; int i = a . size ( ) - 1 , j = b . size ( ) - 1 ; while ( i >= 0 j >= 0 s == 1 ) { s += ( ( i >= 0 ) ? a [ i ] - '0' : 0 ) ; s += ( ( j >= 0 ) ? b [ j ] - '0' : 0 ) ; result = char ( s % 2 + '0' ) + result ; s /= 2 ; i -- ; j -- ; } return result ; } string addBinary ( string arr [ ] , int n ) { string result = " " ; for ( int i = 0 ; i < n ; i ++ ) result = addBinaryUtil ( result , arr [ i ] ) ; return result ; } int main ( ) { string arr [ ] = { "1" , "10" , "11" } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << addBinary ( arr , n ) << endl ; return 0 ; }