原题:
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
翻译:
给你两个二进制字符串,返回他俩的和.
输入字符串都是非空且只包含字符0 1
例 1:
输入: a = "11", b = "1"
输出: "100"
例 2:
输入: a = "1010", b = "1011"
输出: "10101"
C程序
学习的代码
char * addBinary(char * a, char * b){
int alen = strlen(a);
int blen = strlen(b);
int Mlen = alen>blen?alen:blen;
int carry = 0;
char * result = (char*)malloc(Mlen+2);
result[Mlen+1]='\0';
while(alen!=0 || blen!=0)
{
//减去‘0’是为了将字符转化为整形
if(alen)carry += a[--alen]-'0';
if(blen)carry += b[--blen]-'0';
result[Mlen--] = (int)(carry%2) + '0';
carry = (int)(carry/2);
}
//如果不加这字符串的结束标志,就会出现堆溢出
result[0] = carry+'0';
//能直接把数组开头截掉,很好的技巧
return result+(carry^1);
}
总结:
- 可以通过增加数组头地址,能够返回一个被截掉头的数组
- 对于字符串数组,如果后面没有加字符串结束标志‘\0’,那么在进行字符串读取时会发生堆溢出