二进制求和

题目:给定两个二进制字符串,返回他们的和(用二进制表示)。

输入为非空字符串且只包含数字 1 和 0

哇塞,真的吐血了,dev出的来,leetcode一直报溢出,以前总是循环判断数组那出问题,很小心的都改了,还是错

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char * addBinary(char * a, char * b){
	int i,j,k,m=strlen(a),n=strlen(b),t;
	k=m>n?m:n;
	char *s=(char *)malloc(sizeof(char)*(k+1)),plus=0;
	for(i=m-1,j=n-1;i>=0&&j>=0&&k>=0;i--,j--,k--){
		t=0;
		t+=plus;
		if(a[i]=='1') t++;
		if(b[j]=='1') t++;
		plus=t/2;
		t=t%2;
		if(t==0) s[k]='0';
		else if(t==1) s[k]='1';
	}
	if(i>-1){
		for(;i>=0&&k>=0;i--,k--){
			t=0;
			t+=plus;
			if(a[i]=='1') t++;
			plus=t/2;
			t=t%2;
			if(t==0) s[k]='0';
			else if(t==1) s[k]='1';
		}	
	}
	if(j>-1){
		for(;j>=0&&k>=0;j--,k--){
			t=0;
			t+=plus;
			if(b[j]=='1') t++;
			plus=t/2;
			t=t%2;
			if(t==0) s[k]='0';
			else if(t==1) s[k]='1';
		}	
	}
	if(i==j&&plus==1&&k>=0){
		s[k]='1';
		k--;
	}
	return s+k+1;
}
int main(){
	char a[10],b[10];
	gets(a);
	gets(b);
	printf("%s",addBinary(a,b));
} 

看了别人的代码改进后,只要i和j存在或者有进位,就要给结果数组赋值

char * addBinary(char * a, char * b){
	int m=strlen(a),n=strlen(b),t;
	int k=m>n?m:n,i,j;
	char *s=(char *)malloc(sizeof(char)*(k+2)),plus=0;
	s[k+1]='\0';
	for(i=m-1,j=n-1;i>=0||j>=0||plus;i--,j--,k--){
		t=0;
		t+=plus;
		t+=(i>-1?a[i]-'0':0)+(j>-1?b[j]-'0':0);
		plus=t/2;
		t=t%2;
		if(t==0) s[k]='0';
		else if(t==1) s[k]='1';
	}
	return s+k+1;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值