题目
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
分析
计算两个二进制数之和,思路和代码类似于大整数相加,只是十进制改为二进制,对应位数字相加,将进位进上去。
需要注意的是""+"",""+"0","0"+"1"几个特殊的情况。
char* addBinary(char* a, char* b) {
int alength=0,blength=0;
while(a[alength]!='\0')
alength++;
while(b[blength]!='\0')
blength++;
if(alength==0&&blength==0)
{
return "0";
}
char *ans=(char *)malloc(sizeof(char)*(alength+blength+1));
int anslength=0;
int temp=0,i=0;
while(i<alength&&i<blength)
{
temp=temp+a[alength-i-1]-'0'+b[blength-i-1]-'0';
if(temp>1)
{
ans[alength+blength-1-anslength]=temp%2+'0';
temp=temp/2;
}
else
{
ans[alength+blength-1-anslength]=temp+'0';
temp=0;
}
anslength++;
i++;
}
while(i<alength)
{
temp=temp+a[alength-i-1]-'0';
if(temp>1)
{
ans[alength+blength-1-anslength]=temp%2+'0';
temp=temp/2;
}
else
{
ans[alength+blength-1-anslength]=temp+'0';
temp=0;
}
anslength++;
i++;
}
while(i<blength)
{
temp=temp+b[blength-i-1]-'0';
if(temp>1)
{
ans[alength+blength-1-anslength]=temp%2+'0';
temp=temp/2;
}
else
{
ans[alength+blength-1-anslength]=temp+'0';
temp=0;
}
anslength++;
i++;
}
if(temp>0)
{
ans[alength+blength-1-anslength]=temp+'0';
anslength++;
}
printf("%d %d %d\n",alength,blength,anslength);
ans[alength+blength]='\0';
return ans+alength+blength-anslength;
}
网友评论