Add Binary

 67. Add Binary

Easy
8.5K
843
Companies

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:

  • 1 <= a.length, b.length <= 104
  • a and b consist only of '0' or '1' characters.
  • Each string does not contain leading zeros except for the zero itself.

My_Python:
class Solution:
    def addBinary(self, a: str, b: str) -> str:
        if len(a)>len(b):
            short = b
            large = a
        else:
            short = a
            large = b
        carry = 0
        result =""
        while len(short)!=len(large):
            short = "0"+short
        for i in range(len(short)-1,-1,-1):
            add = int(short[i]) + int(large[i]) + carry
            result = str(add%2)+result 
            if add >=2:
                carry = 1
            else:
                carry =0 
        if carry==0:
           return result
        else:
            result = str(carry) + result
            return result

My C++:
class Solution {
public:
    string addBinary(string a, string b) {
        string large,small;
        if (a.length()>b.length())
            {
            large = a;
            small = b;
            }
        else
        {
            {
            large = b;
            small = a;
            }
        }

        while (large.length()!= small.length())
        {
            string zero ="0";
            small = zero + small;
        } 

        int carry = 0;
        string result = "";

        for (int i = small .size()-1;i>=0;i--)
        {
            int add = (small[i]-'0') + (large[i]-'0') + carry;
            result = to_string(add%2)+result ;
            if (add >=2)
                carry = 1;
            else
                carry =0;
        }
        if (carry==0)
           return result;
        else
        {
            result = to_string(carry) + result;
            return result;
        }
        
        
        
    }
    
};
Other Python:
class Solution:
  def addBinary(self, a: str, b: str) -> str:
    s = []
    carry = 0
    i = len(a) - 1
    j = len(b) - 1

    while i >= 0 or j >= 0 or carry:
      if i >= 0:
        carry += int(a[i])
        i -= 1
      if j >= 0:
        carry += int(b[j])
        j -= 1
      s.append(str(carry % 2))
      carry //= 2

    return ''.join(reversed(s))

Other C++:
lass Solution {
 public:
  string addBinary(string a, string b) {
    string ans;
    int carry = 0;
    int i = a.length() - 1;
    int j = b.length() - 1;

    while (i >= 0 || j >= 0 || carry) {
      if (i >= 0)
        carry += a[i--] - '0';
      if (j >= 0)
        carry += b[j--] - '0';
      ans += carry % 2 + '0';
      carry /= 2;
    }

    reverse(begin(ans), end(ans));
    return ans;
  }
};



Comments

Popular posts from this blog