Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Accept: 2ms
char *addBinary(char *a, char *b) {
int len_a = (int)strlen(a);
int len_b = (int)strlen(b);
int len_c = 0;
if (len_a > len_b) {
len_c = len_a + 1;
} else {
len_c = len_b + 1;
}
char *c = malloc(len_c + 1);
c[len_c] = '\0';
int pa = (int)len_a - 1;
int pb = (int)len_b - 1;
int pc = (int)len_c - 1;
int carry = 0;
for (; pa >= 0 && pb >= 0; --pa, --pb, --pc) {
int n = a[pa] - '0' + b[pb] - '0' + carry;
carry = n / 2;
c[pc] = '0' + (n % 2);
}
for (; pa >= 0; --pa, --pc) {
int n = a[pa] - '0' + carry;
carry = n / 2;
c[pc] = '0' + (n % 2);
}
for (; pb >= 0; --pb, --pc) {
int n = b[pb] - '0' + carry;
carry = n / 2;
c[pc] = '0' + (n % 2);
}
if (carry) {
c[pc--] = '1';
}
return &c[pc + 1];
}