67. Add Binary二进制相加
Description
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
本体有点像leetcode 66 plus one,但本题中你需要处理的是字符0/1,而非整数的数组,感觉这个题的等级完全可以设为中等
需要解决的问题:
- 进位相加
- 最高位还有进位
- 字符形式的数字和整形形式的数字加减
- 字符数组表示字符串的标志处理 ‘\0’
char* addBinary(char* a, char* b) {
int alength, blength, length, index;
alength = strlen(a);
blength = strlen(b);
length = alength > blength ? alength : blength;
index = length;
char *retch, *retchp;
int carry = 0;
retch = (char*)malloc(sizeof(char) * (length + 1));//多一是为了多存'\0'
retch[length] = '\0';
while(alength > 0 && blength > 0){//坑1--不能将条件改成alength-- > 0 && blength-- > 0,防止前一个条件不成立,后一个--不执行
if(carry + a[alength - 1] - '0' + b[blength - 1] > '1')//坑2:字符加减一定注意转换
{
if(length == 1){//处理a=“1” b=“1” 的情况
retch = (char *)realloc(retch,sizeof(char) * 3);
retch[0] = '1';
retch[1] = '0';
retch[2] = '\0';
return retch;
}else{
retch[--index] = carry + a[alength - 1] + b[blength - 1] - 2 - '0';//下标是从0开始,得前置--
carry = 1;
}
}else{
retch[--index] = carry + a[alength - 1] + b[blength - 1] - '0';
carry = 0;
}
--alength;
--blength;
}
while(alength > 0)//坑3:不要换成while(alength--),只有alength为0才不循环,可能前面的小改动致使alength为负,引起这儿的死循环
{
if(carry + a[alength-1] > '1'){
retch[--index] = carry + a[alength-1] - 2;
carry = 1;
}else{
retch[--index] = a[alength-1]+carry;
carry = 0;
}
--alength;
}
while(blength > 0)
{
if(carry + b[blength-1] > '1'){
retch[--index] = carry + b[blength-1] - 2;
carry = 1;
}else{
retch[--index] = b[blength-1]+carry;
carry = 0;
}
--blength;
}
if(carry == 1){//处理最高位还有进位的情况,放这儿能有效减少代码量,因为它把a,b长度不一致的情况,while循环后高位的情况也考虑了
retchp = (char*)malloc(sizeof(char) * (length + 2));
retchp[0] = '1';
retchp[length + 1] = '\0';
for(index = 1; index <= length; index++)
{
retchp[index] = retch[index - 1];
}
free(retch);
return retchp;
}
return retch;
}