Problem Statement

Given two binary strings a and b, return their sum as a binary string.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

Constraints:

Problem Link

Add Binary - LeetCode

Code

class Solution {
public:
   
    string addBinary(string a, string b) {
        
        if(a=="0")
            return b;
        
        if(b=="0")
            return a;
        
        int m = a.size();
        int n = b.size();
        int carry = 0;
        int i = m-1;
        int j = n-1;
        string res = "";
        while(carry||i>=0||j>=0)
        {
           int num1 = i>=0 ? a[i]-'0' : 0;
           int num2 = j>=0 ? b[j] - '0' : 0;
            
            
           int sum = num1+num2+carry;
           int digit = sum%2; 
           res+=to_string(digit);
           carry = sum/2; 
            
          
            
          
           i--;
           j--; 
          
            
        }
        
        reverse(res.begin(),res.end());
        
        return res;
       
    }
};