"1"+"11" = "100"
从右向左相加每一位,从左向右保存在新数组中(注意保存进位,如果存在的情况),然后反转新数组,
char* addBinary(char* a, char* b) {
int m = strlen(a);
int n = strlen(b);
char *array = calloc(m>n?m+2:n+2, sizeof(char));//申请最大的空间m,+1(carry), +1('\0')
int sum = 0, carry = 0;
int i = 0;
array[i++] = 0;//先把'\0' 放在第一个位置,最后会整个翻转
while(1){
if(m&&n){// 从后往前相加,反着加
sum = (a[m-1]-'0'+b[n-1]-'0'+carry)%2;
carry = (a[m-1]-'0'+b[n-1]-'0'+carry)/2;
m--;
n--;
}else if(m){
sum = (a[m-1]-'0'+carry)%2;
carry = (a[m-1]-'0'+carry)/2;
m--;
}else if(n){
sum = (b[n-1]-'0'+carry)%2;
carry = (b[n-1]-'0'+carry)/2;
n--;
}else
break;
array[i++] = sum+'0';//每次保存下来当前位的相加和(不算进位carry)
}
if(carry)
array[i++] = '1';
int left = 0;
int right = i-1; //反转整个字符串
while(left < right){
char tmp = array[left];
array[left] = array[right];
array[right] = tmp;
left++;
right--;
}
return array;
}