In this Leetcode Add Binary problem solution we have Given two binary strings a and b, return their sum as a binary string.

Leetcode Add Binary problem solution


Problem solution in Python.

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        carry = 0
        result = ''

        a = list(a)
        b = list(b)

        while a or b or carry:
            if a:
                carry += int(a.pop())
            if b:
                carry += int(b.pop())

            result += str(carry %2)
            carry //= 2

        return result[::-1]



Problem solution in Java.

class Solution {
    public String addBinary(String a, String b) {

        int i = a.length() - 1;
        int j = b.length() - 1;

        StringBuilder sb = new StringBuilder();
        int sum = 0;

        while(i >= 0 || j >= 0){

            sum /= 2;
            if(i >= 0) sum += a.charAt(i) - '0';
            if(j >= 0) sum += b.charAt(j) - '0';

            sb.append(sum % 2);
            i--;
            j--;

        }

        if(sum / 2 != 0) sb.append(1);
        return sb.reverse().toString();
    }
}


Problem solution in C++.

class Solution {
public:
    string addBinary(string a, string b) {
        string result;
        int carry = 0;
        for(int idxA = a.size()-1, idxB = b.size()-1; idxA>=0 || idxB>=0; idxA--, idxB--) {
            int aNum = idxA >=0 ? a[idxA]-'0' : 0;
            int bNum = idxB >=0 ? b[idxB]-'0' : 0;
            int curPosNum = aNum + bNum + carry;
            int tempRe = curPosNum%2;
            carry = curPosNum/2;
            result.insert(result.begin(), tempRe+'0');
        }
        if(carry > 0) result.insert(result.begin(), carry+'0');
        return result;
    }
};


Problem solution in C.

char* addBinary(char* a, char* b) {
  int i = strlen(a) - 1, j = strlen(b) - 1;
  if (i < j) {
    char* t = a;
    a = b, b = t;
    int k = i;
    i = j, j = k;
  }
  const int aLen = i+1;;

  while (i > 0 && j >= 0) {
    a[i] += b[j] - '0';
    a[i - 1] += (a[i] - '0') >> 1;
    a[i] = (a[i] & 1) + '0';
    j--;
    i--;
  }
  if (j == 0)
    a[0] += b[0] - '0';
  else
    while (i > 0 && a[i] > '1') {
      a[i - 1] += (a[i] - '0') >> 1;
      a[i] = (a[i] & 1) + '0';
      i--;
    }

  if (a[0] > '1') {
    char *c = malloc(aLen+2);
    memcpy(c+1, a, aLen);
    c[0] = '0' + ((c[1] - '0') >> 1);
    c[1] = (c[1]&1) + '0';
    c[aLen+1] = 0;
    a = c;
  }
  return a;
}