Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
char* addBinary(char* a, char* b)
{
int lena = strlen(a);
int lenb = strlen(b);
int retlen = lena > lenb ? lena + 2 : lenb + 2;
char *ret = (char *)malloc(sizeof(char) * retlen);
ret[0] = '0';
ret[--retlen] = '\0';
int mark = 0;
char *aend = a + lena - 1;
char *bend = b + lenb - 1;
char *rend = ret + retlen - 1;
while (rend - ret > 0) {
if (aend && bend)
*rend = *aend + *bend + mark - '0';
else if (aend)
*rend = *aend + mark;
else if (bend)
*rend = *bend + mark;
if (*rend >= '2') {
*rend -= 2;
mark = 1;
} else
mark = 0;
if (aend && aend == a)
aend = NULL;
if (bend && bend == b)
bend = NULL;
if (aend) aend--;
if (bend) bend--;
rend--;
}
if (mark)
ret[0] = '1';
return ret[0] == '0' ? ret + 1 : ret;
}