Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
题目:求2个二进制字符串的和,结果也要二进制字符串输出。
1 char* addBinary(char* a, char* b) { 2 int i = strlen(a)-1; 3 int j = strlen(b)-1; 4 int c = 0; 5 char temp; 6 char *p = (char*)malloc(i > j ? i+3 :j+3); //分配字符串空间 7 char *s = p; 8 while(i >= 0 || j >= 0 || c == 1) 9 { 10 c += i >= 0 ? a[i--] - 48 : 0; //字符串每一位相加 11 c += j >= 0 ? b[j--] - 48 : 0; 12 *s++ = c % 2 + 48; 13 c = c/2; //根据c的值每次要进位 14 } 15 *s = '