给你两个二进制字符串 a
和 b
,以二进制字符串的形式返回它们的和。
示例 1:
输入:a = "11", b = "1" 输出:"100"
示例 2:
输入:a = "1010", b = "1011" 输出:"10101"
思路:从末尾开始逐个相加求和,利用mod记录进位的值,用栈来存储数据,通过后进先出实现正序输出。
char * addBinary(char * a, char * b){
int len1=strlen(a);
int len2=strlen(b);
int maxlen=len1>len2 ? len1:len2;
a=a+len1-1;//指向末尾
b=b+len2-1;
int mod=0;//进位
int num1,num2,num,top=-1;
char temp[10001],*res;
while(len1>0 && len2>0)
{
len1--;
len2--;
num1=*a-'0';
a--;
num2=*b-'0';
b--;
num=num1+num2+mod;
if(num==0)
{
temp[++top]='0';
mod=0;
}
else if(num==1)
{
temp[++top]='1';
mod=0;
}
else if(num==2)
{
temp[++top]='0';
mod=1;
}
else{
temp[++top]='1';
mod=1;
}
}
while(len1>0)
{
num1=*a-'0';
a--;
len1--;
num=num1+mod;
if(num==0)
{
temp[++top]='0';
mod=0;
}
else if(num==1)
{
temp[++top]='1';
mod=0;
}
else
{
temp[++top]='0';
mod=1;
}
}
while(len2>0)
{
num2=*b-'0';
b--;
len2--;
num=num2+mod;
if(num==0)
{
temp[++top]='0';
mod=0;
}
else if(num==1)
{
temp[++top]='1';
mod=0;
}
else{
temp[++top]='0';
mod=1;
}
}
if(mod==1)
{
temp[++top]='1';
}
res=(char *)malloc(sizeof(char)*(top+2));
maxlen=top+1;
while(top>=0)
{
*(res)=temp[top--];
res++;
}
*res='\0';
res-=maxlen;
return res;
}
如果对您有帮助的话点个赞呗~