Add Binary Strings | Practice | GeeksforGeeks

Given two binary strings A and B consisting of only 0s and 1s. Find the resultant string after adding the two Binary Strings.
Note: The input strings may contain leading zeros but the output string should not have any leading zeros.

Example 1:
Input:
A = "1101", B = "111"
Output: 10100
Explanation:
 1101
+ 111
10100

Example 2:
Input: 
A = "10", B = "01"
Output: 11
Explanation: 
  10
+ 01
  11


Your Task:
You don't need to read input or print anything. Your task is to complete the function addBinary() which takes 2 binary string A and B and returns a binary string denoting the addition of both the strings.

Expected Time Complexity: O(max(|A|, |B|)).
Expected Auxiliary Space: O(max(|A|, |B|)) (for output string).

Constraints:
1 ≤ |A|, |B| ≤ 106
0
mahesh_phutane1 week ago
java solution
class Solution {
    String addBinary(String A, String B) {
        int alen = A.length();
	    int blen = B.length();
	    int i = alen-1,j = blen-1;
	    int carry = 0;
	    StringBuilder sb = new StringBuilder("");
	    while(i != -1 || j != -1 || carry!= 0){
	    int Asum = (i != -1)? A.charAt(i--) - '0': 0;
	    int Bsum = (j != -1)? B.charAt(j--) - '0': 0;
	        
	    int sum = carry + Asum + Bsum;
	    sb.append(Integer.toString(sum % 2));
	    carry = sum / 2;
	}
	j = sb.length() - 1;
	while(sb.charAt(j) != '1') {  
	    sb.deleteCharAt(j);
	    j--;
	    
	}
// 	StringBuilder res = sb.reverse();
	return sb.reverse().toString();
    }
}
 
+1
szlachetk1 month ago
Okay so input numbers CAN have leading 0's but output CAN'T what a bullshit
0
hanumanmanyam8372 months ago
WHY iam getting TLE?
String addBinary(String A, String B) {
        // code here
        String res = "";
        int carry=0;
        int i=A.length()-1;
        int j=B.length()-1;
        while(i>=0 || j>=0)
        {
            int Asum=(i>=0)? Character.getNumericValue(A.charAt(i)) : 0;
            int Bsum=(j>=0)? Character.getNumericValue(B.charAt(j)) : 0;
            int sum=Asum+Bsum+carry;
            carry=sum/2;
            sum=sum%2;
            res=sum+res;
            i--;
            j--;
        }
        if(carry==1)
        {
            res=carry+res;
        }
        int k=0;
        while(res.charAt(k)=='0')
        {
            k++;
        }
        res = res.substring(k, res.length());
        
        return res;
        
    }
+2
anantkumawat101102 months ago
C++ Solution.
string addBinary(string A, string B){
	string str = "";
	int sum, Asum, Bsum, carry = 0;
	int i = A.length() - 1, j = B.length() - 1;
	    
	while(i != -1 || j != -1 || carry){
	    Asum = (i != -1)? A[i--] - '0': 0;
	    Bsum = (j != -1)? B[j--] - '0': 0;
	        
	    sum = carry + Asum + Bsum;
	    str += to_string(sum % 2);
	    carry = sum / 2;
	}
	j = str.length() - 1;
	while(str[j] != '1') { str.pop_back(); j--;}
	reverse(str.begin(), str.end());
	return str;
	}
0
devendray21062 months ago
My code is giving TLE what optimization should I do ?
	string addBinary(string A, string B)
	{
	    string ans;
	    
	    //To remove trailing zeros
	    int i=0;
	    while(i<A.length() && A[i]=='0'){
	        A.erase(A.begin()+0);
	    }
	    i=0;
	    while(i<B.length() && B[i]=='0'){
	        B.erase(B.begin()+0);
	    }
	    
	    
	    int c=0;
	    int n = A.length()-1;
	    int m = B.length()-1;
	    while(n>=0 && m>=0){
	        if((A[n]=='0' && B[m]=='1')||(A[n]=='1' && B[m]=='0')){
	            if(c==0){
	                ans.insert(0,"1");
	            }
	            else{
	                ans.insert(0,"0");
	                c=1;
	            }
	        }
	        else if(A[n]=='1' && B[m]=='1'){
	            if(c==0){
	                ans.insert(0,"0");
	                c=1;
	            }
	            else{
	                ans.insert(0,"1");
	                c=1;
	            }
	        }
	        else if(A[n]=='0' && B[m]=='0'){
	            if(c==0){
	                ans.insert(0,"0");
	            }
	            else{
	                ans.insert(0,"1");
	                c=0;
	            }
	            
	        }
	        n--;
	        m--;
	        
	    }
	    

	    while(n>=0){
	        if(c==0){
	            if(A[n]=='1'){
	                ans.insert(0,"1");
	            }
	            else if(A[n]=='0' && n>0){
	                ans.insert(0,"0");
	            }
	        }
	        else{
	            if(A[n]=='1'){
	                ans.insert(0,"0");
	                c=1;
	            }
	            else{
	                ans.insert(0,"1");
	                c=0;
	            }
	        }
	        n--;
	    }
	    while(m>=0){
	        if(c==0){
	            if(B[m]=='1'){
	                ans.insert(0,"1");
	            }
	            else{
	                ans.insert(0,"0");
	            }
	        }
	        else{
	            if(B[m]=='1'){
	                ans.insert(0,"0");
	                c=1;
	            }
	            else{
	                ans.insert(0,"1");
	                c=0;
	            }
	        }
	        m--;
	    }
	    if(c==1){
	        ans.insert(0,"1");
	    }
	    return ans;
	}
0
neeramrutia3 months ago
 int i;       StringBuilder A1=new StringBuilder(A);       StringBuilder B1=new StringBuilder(B);       for(i=0;;)       {           if(A1.charAt(i)=='0' && A1.length()>1)           {              A1.deleteCharAt(i);              i++;           }           else           {               break;           }       }      String ans1=A1.toString();               for(i=0;;)       {           if(B1.charAt(i)=='0' && B1.length()>1)           {               B1.deleteCharAt(i);               i++;           }           else           {               break;           }       }       String ans2=B1.toString();              int a=Integer.parseInt(A,2);         int b=Integer.parseInt(B,2);        int c=a+b;       String s=Integer.toBinaryString(c);       return s;
0
hemantnegi135793 months ago
java.math.BigInteger a = new java.math.BigInteger(A, 2); java.math.BigInteger b = new java.math.BigInteger(B, 2);
        java.math.BigInteger sum= a.add(b);
        String s = sum.toString(2);
        return s;
0
rdm1233 months ago
def addBinary(self, A, B):    m=int(A,2)    # m=m[2:]    n=int(B,2)    p=m+n    return bin(p).replace("0b","")
+3
nitinsaini9964 months ago
string addBinary(string A, string B)
	{
	    // your code here
	    int i = A.length()-1;
	    int j = B.length()-1;
	    
	    int carry =0;
	    string result;
	    while(i>=0 || j>=0){
	        int sum = carry;
	        if(i>=0) sum += A[i--] - '0';
	        if(j>=0) sum += B[j--] - '0';
	        
	        carry = sum>1?1:0;
	        result += to_string(sum%2);
	    }
	    if(carry)   result += to_string(carry);
	    reverse(result.begin(),result.end());
	    int index0 = 0;
        while(index0 < result.size() and result[index0] =='0')
        {
            index0++;
        }
        
        return result.substr(index0);
	   
	    
	}
0
2001shivank4 months ago
Java Users will face issue here(TLE), so go and learn StringBuilder and StringBuffer.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.